如何将以下linux文件中的hello替换为hello1,并将hello的下一个问题替换为hello2,直到文件末尾为止

时间:2017-08-28 07:28:46

标签: linux shell perl awk sed

This is a test script hello.
This is hello a test script.
This hello is a test script hello.
This is a test script hello.
hello This is a test script hello.

搜索但无法使用awk或sed命令找到上面的正确解释。 任何指导将受到高度赞赏。

我尝试下面的命令需要对下面的一些修改在每个数字之前打印hello字符串

awk '{for(x=1;x<=NF;x++)if($x~/hello/){sub(/hello/,++i)}}1' file.txt > new.txt

输出:

This is a test script 1. 
This is 2 a test script. 
This 3 is a test script 4. 
This is a test script 5. 
6 This is a test script 7. 

3 个答案:

答案 0 :(得分:3)

perl -pe's/hello\K/++$x/ge'  input.txt

这会增加每个hello的计数,从1开始。 \Kpositive lookbehind

答案 1 :(得分:1)

awk仍然适用于您的请求,修改您的命令,

awk '{for(x=1;x<=NF;x++)if($x~/hello/){sub(/hello/,"&"++i,$x)}}1' file.txt > new.txt

简要说明,

  • &中的sub被替换为实际匹配的文字,即"hello"
  • 您可以为sub添加第三个参数,仅处理$x

答案 2 :(得分:0)

使用GNU awk进行单词边界:

$ awk '{while(sub(/\<hello\>/,"&"c+1))c++;}1' file
This is a test script hello1.
This is hello2 a test script.
This hello3 is a test script hello4.
This is a test script hello5.
hello6 This is a test script hello7.