使用sed,如何替换文件中的特定内容?

时间:2015-07-31 09:46:52

标签: regex bash sed

我在xml文件中有以下文字:

 <Connector port="8983" protocol="HTTP/1.1"
               connectionTimeout="20000"
               URIEncoding="UTF-8"
               redirectPort="8443" />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the JSSE configuration, when using APR, the
         connector should be using the OpenSSL style configuration
         described in the APR documentation -->
    <!--
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->

作为构建脚本的一部分,我需要将8983端口替换为另一个端口号,比如说8181.所以我只需要更改上面的第一行(忽略任何行号,因为这行可能出现在文件的任何地方)。此外,不依赖端口号,在这种情况下它是8983但它可能是其他的东西。总结一下:我需要更改模式第一次出现的数字\Connector port="\d{4}" protocol="HTTP\/1.1$\

我试过

sed 's#Connector port="\d{4}" protocol="HTTP/1.1"#Connector port="8181" protocol="HTTP/1.1"#' -i server.xml

没有错误,但对文件没有影响。

最好的方法是什么?

PS:服务器运行Ubuntu 12.04

1 个答案:

答案 0 :(得分:0)

在Linux上(我在Ubuntu上测试过):

sed -i 's/Connector port="8983" protocol="HTTP\/1.1"/Connector port="8181" protocol="HTTP\/1.1"/' server.xml

在OSX上(在10.10上测试):

sed -i '' 's/Connector port="8983" protocol="HTTP\/1.1"/Connector port="8181" protocol="HTTP\/1.1"/' server.xml
相关问题