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 -
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.
CodePudding user response:
This might work for you (GNU sed):
sed -z 's/foo/bar/2' file
Slurps the whole for file into the pattern space and replaces the second occurrence of foo
with bar
.
Alternative:
sed 'H;$!d;x;s/.//;s/foo/bar/2' file
CodePudding user response:
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 substitutions/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.