sed - perform only first (nth) matched replacement?
I have seen it somewhere else on this site:
sed '/1/{s/1/5/;:a;n;ba}' ztest
So once you found the 1st occurrence, you loop till the end of the file reading and printing lines.
Update
It can be enhance to only replace the Nth match. The idea is to store a X
at each match in the holdspace, and when all the X
s are there, loop till the end of file. Bellow, the script that replace the 2nd occurrence:
sed '/1/{G;s/\nX\{1\}//;tend;x;s/^/X/;x;P;d};p;d;:end;s/1/5/;:a;n;ba'
Note that you need to put (N-1) between the \{
and \}
.
Update 2
I realize that the P;d
above is useless if the p;d
is replaced by P;d
. So a simpler solution is:
sed '/1/{G;s/\nX\{1\}//;tend;x;s/^/X/;x};P;d;:end;s/1/5/;:a;n;ba'
Don't know if that's doable with sed
, but here's an awk
version.
awk 'BEGIN {matches=0}
matches < 2 && /1/ { sub(/1/,"5"); matches++ }
{ print $0 }' ztest
This will replace 1
with 5
for the first two matches of 1
. (Change the 2
in there to increase/decrease the number of matches you want.)
After that, the file is printed as-is.
This might work for you (GNU sed):
sed '0,/1/s//5/' file