Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

$ 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

share|improve this question
add comment

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
share|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 '12 at 19:46
add comment

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
share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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