$ 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 txt.
like: sed -i "MAGIC" file.txt

link|improve this question

62% accept rate
feedback

3 Answers

up vote 2 down vote accepted

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
link|improve this answer
+1 for the unfortune that arises. – bubu Jan 23 '11 at 11:21
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 at 19:46
feedback

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
link|improve this answer
feedback

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.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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