Sed paste after ONLY the first line match?

Trying to do this:

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

in the example text:

 Line1 Line2 MatchMeOnce Line4 MatchMeOnce Line6 

How can I make it match only the very first appearance of the record and match not in the next lines?

 Line1 Line2 MATCHED Line4 MatchMeOnce Line6 
+6
source share
4 answers

This might work for you:

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

This will work for all sed options if MatcMeOnce is on the second line or higher, or this (GNU sed):

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

which satisfies the condition above the edge:

Or another alternative (all sed) that dumps the entire file into memory:

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

which has the additional advantage that if you want to select the nth and not the 1st from MatchMeOnce , all you need to do is change the appearance flag, i.e. change second occurrence:

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

To change the last use, use:

 sed ':a;$!{N;ba};s/\(.*)MatchMeOnce/\1MATCHED/' file 
+7
source

sed (not so obvious):

 sed '1,/^MatchMeOnce$/ {/^$/\c MATCHED }' 

awk (obviously):

 BEGIN { matched = 0 } /^MatchMeOnce$/ { if (matched == 0) { print "MATCHED" matched = 1 next } } { print } 

perl also cool ...

Hope it works more or less :-)

+2
source
 $ sed '/MatchMeOnce/{s//MATCHED/;:a;n;ba}' input.txt Line1 Line2 MATCHED Line4 MatchMeOnce Line6 
+2
source

GNU sed has a t command to branch to the end of the script (alternatively this label) when any substitution matches.

Personally, I use perl -ne and perl -ane (and I believe some people use Ruby) if the awk or sed solution is not dazzlingly obvious. But I understand that for some systems it is still possible to have awk and sed without Perl and make installing Perl difficult; and that some programmers prefer awk and sed independently.

+1
source

Source: https://habr.com/ru/post/911716/


All Articles