6
$ echo -e "AsometAhingA\nsomethingA\nASomethiAng"
AsometAhingA
somethingA
ASomethiAng
$ echo -e "AsometAhingA\nsomethingA\nASomethiAng" | sed "s/A//"
sometAhingA
something
SomethiAng
$

I know that sed "s/A//" deletes the first match in every line. But I want to delete only the first match in a text file or stream. How can I do this?   Like: sed -i "MAGIC" file.txt

1
6

Unfortunately, MAGIC is not a sed command, so you will have to use something else:

sed -i '0,/A/ s///' file.txt
perl -i -pe 'if (!$changed) {s/A// and $changed++;}' file.txt
echo -e "/A/ s///\nwq" | ed file.txt
1
  • In your sed solution, would it still work if "AsometAhingA" was the SECOND or later line, with "A" not happening anywhere prior?
    – Marcos
    May 7 '12 at 19:46
7

As long as it's GNU sed (which it probably is, since it's Fedora), you should be able to do:

sed '0,/RE/{//d;}' file.txt
1
  • 1
    Do you know if the semicolon is required? It seems to work without it for me, but I don't want to run into difficulties down the road.
    – wchargin
    Nov 18 '14 at 20:33
2

If you have a version of sed (non-GNU) that doesn't support 0 as a line address, then you can do this:

sed '/A/{s///;:a;n;ba}' file.txt

It prints each line as is until it finds one with the pattern. Then it deletes the pattern. After that it loops from ba (branch to "a") to :a (label "a") and reads and prints each line without looking for the pattern again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.