Issue
I'm using centos 7. sed command to replace second occurrence not working to me. I tried the following solutions - href="https://stackoverflow.com/questions/46238843/sed-replace-at-second-occurrence">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.
Solution
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
Answered By - potong Answer Checked By - Marilyn (WPSolving Volunteer)