I'm using centos 7. sed command to replace second occurrence not working to me. I tried the following solutions:
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.
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