Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace the nth occurrence of a string using sed

Tags:

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.

like image 237
Raoul Avatar asked Dec 11 '12 10:12

Raoul


People also ask

How do you change a string in a sed file?

The procedure to change the text in files under Linux/Unix using sed: Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace.

Which sed command is used for replacement?

The s command (as in substitute) is probably the most important in sed and has a lot of different options. The syntax of the s command is ' s/ regexp / replacement / flags '.


1 Answers

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 '\n' '^' < file | sed 's/jack/jill/2' | tr '^' '\n'
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
like image 87
dogbane Avatar answered Sep 23 '22 07:09

dogbane