sed not working as I expected. What can be the possible reason?

# cat test
<abc>
</abc>
<abc>

</abc>
# sed 's/abc/checker/' test>test1
# cat test1
<checker>
</checker>
<checker>
</checker>
#

I want the first instance of abc to be changed to checker. But all(rest 3 also) are changed. I din't used global (g) option too..

What can be the possible reason for this... Am i doing anything incorrectly here...

Thanks
Ugenther

sed processes files line-by-line - the 'g' option refers to instances of the pattern on the addressed line(s), not the whole file.

If you want to restrict the substitution to parts of the input file you'll need to supply an address, e.g.:

sed '0,/abc/{s/abc/checker/}' test>test1

(addresses from line 0 to the first instance of abc )

1 Like
#sed '0,/abc/{s/abc/checker/}' test>test1

sed: command garbled: 0,/abc/{s/abc/checker/}

Am I mentioning the address incorrectly??
What can be the address for "abc" in the file test. #doubt

Any other alternate ways to replace the word(first instance) to another.

I was using GNU sed 4.1.5, the syntax may be slightly different on whatever implementation your system has (it might insist on whitespace between the address & command, for instance) - check man sed .

Also, if you're on SunOS then try /usr/xpg4/bin/sed .

you can try

sed '1s/abc/checker/' test > test1

Try:

awk '! found && sub(from,to){found=1}1' from=abc to=checker infile
perl -0777pe 's/abc/checker/' infile

@CarloM: 0,.. is GNU sed only , other seds know only 1,.. (and there needs to be a ";" before the closing "}" )