8

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
Jé Queue
  • 10,359
  • 13
  • 53
  • 61
  • Does this answer your question? [How to use sed to replace only the first occurrence in a file?](https://stackoverflow.com/questions/148451/how-to-use-sed-to-replace-only-the-first-occurrence-in-a-file) – rogerdpack Jan 02 '20 at 23:37

4 Answers4

7

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
potong
  • 55,640
  • 6
  • 51
  • 83
2

sed (not so obvious):

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

awk (obvious):

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

perl is also cool...

Hope it more or less works :-)

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
tchap
  • 1,047
  • 8
  • 10
1

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

Personally I use perl -ne and perl -ane (and I suppose some people use Ruby) unless the awk or sed solution is blindingly obvious. But I realize it's still possible for some systems to have awk and sed without Perl and to make it difficult to install Perl; and that some programmers prefer awk and sed regardless.

minopret
  • 4,726
  • 21
  • 34
1
$ sed '/MatchMeOnce/{s//MATCHED/;:a;n;ba}' input.txt
Line1
Line2
MATCHED
Line4
MatchMeOnce
Line6
kev
  • 155,172
  • 47
  • 273
  • 272