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
Use sed 's insert ( i ) option which will insert the text in the preceding line.
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.
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.
The ^ character is what instructs the sed command to add a character to the beginning of each line.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With