delete only first hit /match with sed

5

1

$ 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

LanceBaynes

Posted 2011-01-23T10:15:15.757

Reputation: 3 510

http://stackoverflow.com/questions/148451/how-to-use-sed-to-replace-only-the-first-occurrence-in-a-file – Ciro Santilli 新疆改造中心法轮功六四事件 – 2016-04-26T13:57:32.780

Answers

5

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

user1686

Posted 2011-01-23T10:15:15.757

Reputation: 283 655

In your sed solution, would it still work if "AsometAhingA" was the SECOND or later line, with "A" not happening anywhere prior? – Marcos – 2012-05-07T19:46:50.293

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

Matthieu Cartier

Posted 2011-01-23T10:15:15.757

Reputation: 3 422

1Do 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 – 2014-11-18T20:33:56.990

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.

Paused until further notice.

Posted 2011-01-23T10:15:15.757

Reputation: 86 075