Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sed replace second occurrence in file not working

I’m using centos 7. sed command to replace second occurrence not working to me.
I tried the following solutions –
Sed replace at second occurrence
Sed/Awk to delete second occurence of string – platform independent
sed: How to delete second match in a file
https://unix.stackexchange.com/questions/18303/sed-delete-all-occurrences-of-a-string-except-the-first-one

The file

this
foo
is
a test
file
this
foo

I am trying to run –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sed 's/foo/bar/2g' file
sed 's/foo/bar/2' file
sed -i 's/foo/bar/2g' file

I wish to replace all occurrences of "foo" with "bar" from the second one.

>Solution :

This will perform a substitution on the second and all subsequent lines containing the specified pattern (/foo/):

sed ':1; /foo/! { n; b1 }; :2; n; s/foo/bar/; b2' file

It has two parts:

  • :1; /foo/! { n; b1 }; is a loop, reading lines and outputting them unchanged until the first is encountered that matches /foo/.
  • :2; n; s/foo/bar/; b2 is a loop that repeatedly outputs the current line, reads the next and performs the substitution s/foo/bar/. The substitution is a harmless no-op for lines that do not contain the pattern.

The first match to the pattern is the current line at the beginning of the second loop, so it is output unchanged when second loop first executes its n command.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading