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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8909023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:20:41  来源:igfitidea点击:

Using sed to find and replace a range of numbers

regexbashsedsh

提问by Jarob22

first poster here.

第一张海报在这里。

Trying to use sed to find and replace a word. Code is as follows:

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

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

And I'd run the file like this:

我会像这样运行文件:

./choosePort.sh 3001

When I run this code, there are no errors given like bad regex format, it just doesn't replace anything and the contents of tempXml.xml are just the contents of ConnectionConfig, unchanged.

当我运行此代码时,没有给出错误的正则表达式格式之类的错误,它只是不替换任何内容,并且 tempXml.xml 的内容只是 ConnectionConfig 的内容,未更改。

What I'd like to be able to do is recognise any number 3000 - 3099 in the 30?? part of the expression, which I thought was what the '?' did.

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

The input line I'm trying to change is:

我试图改变的输入行是:

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

Thanks in advance. (Ip and authkeys in file blanked out for security reasons).

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

回答by dogbane

Use [0-9]instead of ?to match a single digit.

使用[0-9]而不是?匹配单个数字。

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

回答by ezdazuzena

To match a number you can use [0-9]\{2}or \d\{2}

要匹配一个数字,您可以使用[0-9]\{2}\d\{2}

In your case ??would also match 30only.

在你的情况下??30只会匹配。

You can find a nice overview of regular expressions here.

您可以在此处找到对正则表达式的很好的概述。

回答by Pavel Tankov

First, the matching expression must be 30..not 30??
Then, you seem to have forgotten the -eargument to sed.
Try with:

首先,匹配的表达式肯定30..不是30??
然后,你似乎忘记了-e给 sed的参数。
尝试:

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

回答by potong

This might work for you:

这可能对你有用:

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