使用sed查找并替换一系列数字

时间:2012-01-18 11:05:21

标签: regex bash sed sh

这里的第一张海报。

尝试使用sed来查找和替换单词。代码如下:

configFile=ConnectionConfig.xml
sed 's/30??\" authentication=\"someuniqueauthkey/'$1'\" authentication=\"someuniqueauthkey/' $configFile

我会像这样运行文件:

./choosePort.sh 3001

当我运行这段代码时,没有像错误的正则表达式格式那样给出错误,它只是没有替换任何内容,而tempXml.xml的内容只是ConnectionConfig的内容,没有改变。

我希望能够做到的是识别30?30中的任何数字3000 - 3099?表达的一部分,我认为是什么?'?'那样。

尝试更改的输入行是:

<host id="0" address="someip" port="3001" authentication="someauthkey"

提前致谢。 (出于安全原因,文件中的IP和authkeys被清空)。

4 个答案:

答案 0 :(得分:3)

使用[0-9]代替?来匹配单个数字。

sed 's/30[0-9][0-9]\" authentication=\"someuniqueauthkey/'$1'\" authentication=\"someuniqueauthkey/' $configFile

答案 1 :(得分:1)

要匹配某个号码,您可以使用[0-9]\{2}\d\{2}

在您的情况下,??也只会匹配30

您可以找到正则表达式here的精彩概述。

答案 2 :(得分:1)

首先,匹配表达式必须是30..而不是30??
然后,你似乎忘记了sed的-e论证 试试:

sed -e 's/30..\" authentication=\"someuniqueauthkey/'$1'\" authentication=\"someuniqueauthkey/' $configFile

答案 3 :(得分:0)

这可能对您有用:

sed 's/30[0-9][0-9]\(" authentication="someuniqueauthkey\)/'$1'\1/' $configFile