linux - 如何将下面linux文件中的hello替换为hello1,并将下一次出现的hello替换为hello 2,依此类推,直到文件末尾

标签 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. 

最佳答案

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

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

关于linux - 如何将下面linux文件中的hello替换为hello1,并将下一次出现的hello替换为hello 2,依此类推,直到文件末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45913824/

相关文章:

javascript - 表单提交后邮政编码格式错误

linux - git: 'http-push' 不是 git 命令。致命:git-http-push 失败

python - 如何让 linux(raspberry) 在插件电源时运行 python 脚本?

linux - 如何使用 fortran 或 shell 在同一文件中突出显示其右侧的不匹配数据?

python - Emacs 中的 IPython。快速代码评估

bash - 将多个 CSV 行与大多数空字段合并为每个时间戳的单行

Perl 只读取文件的最后一行?

linux - 执行每个 git 命令后如何在 git bash 中打印时间戳?

c++ - std::system 即使在父进程退出后也会执行吗?

unix - 如何在 KornShell 中自定义显示提示以显示主机名和当前目录?