Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
692 views
in Technique[技术] by (71.8m points)

How to replace the nth occurrence of a string using sed

Is there any way to replace the nth occurrence of a string in a file using sed?

I'm using sed -i '0,/jack.*/ s//jill/' to replace the first occurrence.

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

I don't know the value after jack=, it can be anything or nothing.

I want to replace the 2nd occurrence of jack= and anything that follows it with jill.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

For n=2, the command is:

$ tr '
' '^' < file | sed 's/jack/jill/2' | tr '^' '
'
first line
second line
third line
jack
fifth line
jill
seventh line

Update:

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

Alternatively, use awk:

$ awk '/jack/{c+=1}{if(c==2){sub("jack","jill",$0)};print}' file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...