7
$ 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

3 Answers 3

7

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? Commented May 7, 2012 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. Commented Nov 18, 2014 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.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.