I would like to sed
only the last match pattern of a text file.
input file:
boy
boy
girl
boy
output file:
boy
boy
girl
boys
I would like to sed
only the last match pattern of a text file.
input file:
boy
boy
girl
boy
output file:
boy
boy
girl
boys
One method would be to reverse the file, replace only the first match, and then reverse it back again.
tac <file> | sed '1 s/boy/boys/' | tac | sponge <newfile>
tac will "concatenate and print files in reverse". sponge will "soak up standard input and write to a file". It's in the "moreutils" package on debian.
All you need is $
:
sed '$s/boy/boys/'
This might work for you (GNU sed):
sed '1h;1!H;$!d;x;s/.*boy/&s/' file
Slurp the file into memory and substitute the last occurrence of the desired string using greed.
An alternative, less memory intensive solution:
sed '/.*boy/,$!b;//{x;//p;x;h};//!H;$!d;x;s//&s/' file
This uses the hold space to hold previous lines that contain the required string and sheds them when a new occurence of the required string is encountered. At the end of the file the last occurrence is in the hold space and is modified.
Another solution:
sed -z 's/.*boy/&s/' file