如何在文档中使用正则表达式对字符串进行完全匹配,以对单词后的所有内容进行修改

问题描述

我有一个名为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 '/\bthis-is-name-1\b/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
....

但是在那之后,我希望能够替换单词之后的行中的所有内容,并将其替换为1以使其看起来像这样

this-is-name-1 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
....

我使用以下命令, sed -i '/\bthis-is-name-1\b/s/$/ 1/' listofnames.txt 但是我明白了,

this-is-name-1 0 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
....

我该如何修复代码,正确的命令是什么?

解决方法

如果您对awk感到满意,请尝试以下操作。使用GNU awk中显示的示例编写和测试。另外,您的shell变量在分配时不应包含空格。

currentname='this-is-name-1'
awk -v str="$currentname" '$0 ~ "^"str"$"{print $0,1;next} 1' Input_file > temp && mv temp Input_file

说明: 添加以上详细说明。

awk -v str="$currentname" '    ##Starting awk program from here and setting variable str value to shell variable currentname here.
$0 ~ "^"str"$"{                ##Checking if line starts with str and ends with it.
  print $0,1                   ##Printing current line and 1 here.(change 0 to get 0 printed here)
  next                         ##next will skip all further statements from here.
}
1                              ##1 will print edited/non-edited lines here.
' Input_file                   ##Mentioning Input_file name here.
,

另一种gnu-awk命令,该命令在两种情况下均可工作,并且可以内联保存更改。

# place 0 in the end
awk -i inplace -v n='0' -v s='this-is-name-1' '$1 == s { $2 = n } 1' file

# place 1 in the end
awk -i inplace -v n='1' -v s='this-is-name-1' '$1 == s { $2 = n } 1' file

在python中运行它:

import subprocess

currentname = 'this-is-name-1'
argList = ["awk","-i","inplace","-v","n=1","s=" + currentname,'$1 == s{$2 = n} 1','file']

subprocess.call(argList)