如何在文档中使用正则表达式对字符串进行完全匹配

问题描述

我有一个名为listofnames.txt文件

this-is-name-1
this-is-name-2
...
this-is-name-11
this-is-name-12
this-is-name-13
this-is-name-14
...
this-is-name-21
....

我想对某个单词进行完全匹配,然后在其旁边添加一个“ 0”。我使用以下命令:

sed -i '/this-is-name-1/s/$/ 0/' ~/listofnames.txt

但是,代替这个,

this-is-name-1 0
this-is-name-2
...
this-is-name-11
this-is-name-12
this-is-name-13
this-is-name-14
...
this-is-name-21
....

我明白了

this-is-name-1 0
this-is-name-2
...
this-is-name-11 0
this-is-name-12 0
this-is-name-13 0
this-is-name-14 0
...
this-is-name-21
....

我的命令出了什么问题?我该如何解决它并做我需要的事情。似乎是在进行部分比赛,而不是全部比赛。

解决方法

您只需要添加字符串的开头/结尾(默认为sed的行)锚点即可:

sed 's/^this-is-name-1$/& 0/' file
,

您必须匹配单词:this-is-name-1,以便排除诸如this-is-name-11等的情况。有许多方法可以执行此操作,具体取决于文件内容的其余部分以及所需的情况以保护您的编辑。例如\b匹配单词赏金,其中包括空格字符,行的开头/结尾以及其他非字母数字字符。看来对您的情况有好处:

sed -i '/\bthis-is-name-1\b/s/$/ 0/' file

您会发现此阅读非常有用:Reference - What does this regex mean?