问题描述
有没有办法用sed替换文件中第n次出现的字符串?
Is there any way to replace the nth occurrence of a string in a file using sed?
我使用 sed -i '0,/jack.*/s//jill/'
来替换第一次出现.
I'm using sed -i '0,/jack.*/ s//jill/'
to replace the first occurrence.
如何更改它以替换第 n 次出现?
How can i change it so that it replaces the nth occurrence?
我的文件包含以下几行:
My file contents the following lines:
first line
second line
third line
jack=1
fifth line
jack=
seventh line
我不知道 jack=
之后的值,它可以是任何东西,也可以什么都不是.
I don't know the value after jack=
, it can be anything or nothing.
我想用 jill
替换第二次出现的 jack=
及其后的任何内容.
I want to replace the 2nd occurrence of jack=
and anything that follows it with jill
.
推荐答案
首先使用 将所有换行符替换为文件中其他任何地方都没有出现的唯一字符(例如
.您需要这样做才能为 ^
)trsed
创建单个字符串.然后将它传递给 sed
并告诉它替换第 n 次出现的字符串.最后,通过 tr
将输出传回以重新创建换行符.
First replace all the newlines with a unique character that does not occur anywhere else in your file (e.g. ^
) using tr
. You need to do this in order to create a single string for sed
. Then pass it to sed
and tell it to replace the nth occurrence of your string. Finally, pass the output back through tr
to recreate the newlines.
对于 n=2,命令是:
For n=2, the command is:
$ tr '\n' '^' < file | sed 's/jack/jill/2' | tr '^' '\n'
first line
second line
third line
jack
fifth line
jill
seventh line
更新:
也可以使用 sed
完成,无需先更改换行符,使用以下命令:
It can also be done with sed
, WITHOUT changing the newlines first, using the following command:
$ sed ':a;N;$!ba;s/jack/jill/2' file
或者,使用 awk
:
$ awk '/jack/{c+=1}{if(c==2){sub("jack","jill",$0)};print}' file
这篇关于如何使用sed替换第n次出现的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!