Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed insert after ONLY the first line match?

Tags:

unix

sed

Trying to do this:

sed -e '/^MatchMeOnce/i\
MATCHED'

on the example text:

Line1
Line2
MatchMeOnce
Line4
MatchMeOnce
Line6

How can I get it to only match the very first record occurrence and to not match on subsequent lines?

Line1
Line2
MATCHED
Line4
MatchMeOnce
Line6
like image 856
Jé Queue Avatar asked Mar 27 '12 02:03

Jé Queue


People also ask

How do you insert a first line using sed?

Use sed 's insert ( i ) option which will insert the text in the preceding line.

How do you insert a line break in sed?

The "a" command to sed tells it to add a new line after a match is found. The sed command can add a new line before a pattern match is found. The "i" command to sed tells it to add a new line before a match is found.

How do I add a line to a certain line number?

In the first line, we added the line number for insertion. Secondly, we specified the insert action in the same line. Then, in the next line, we added the phrase we wanted to insert. In the end, we need to put a dot (.) to end the input mode and then add xit to save the changes and quit the editor.

How do you add a string at the beginning of each line in Unix?

The ^ character is what instructs the sed command to add a character to the beginning of each line.


1 Answers

This might work for you:

sed '1,/MatchMeOnce/s//MATCHED/' file

This will work for all variations of sed as long as MatcMeOnce is on the 2nd line or greater, or this (GNU sed):

sed '0,/MatchMeOnce/s//MATCHED/'  file

which caters for above edge condition:

Or another alternative (all sed's) which slurps the entire file into memory:

sed ':a;$!{N;ba};s/MatchMeOnce/MATCHED/' file

which has the added advantage in that if you want to choose the nth rather than the 1st of MatchMeOnce all you need do is change the occurrence flag i.e. to change the second occurrence:

sed ':a;$!{N;ba};s/MatchMeOnce/MATCHED/2' file

To change the last occurrence use:

sed ':a;$!{N;ba};s/\(.*)MatchMeOnce/\1MATCHED/' file
like image 57
potong Avatar answered Dec 06 '22 11:12

potong