You can edit up to the first match using sed
:
sed -e '1,/pattern/{s/pattern/replace/;}'
On lines 1 to N-1 (where line N contains the pattern), the substitution does nothing; on line N, it does the real work. Thereafter, you're no longer in the 1,/pattern/
range of lines so there is no further transformation.
Note that this doesn't work if line 1 matches the pattern; it then makes changes in line 1 and the next line that matches the pattern. With GNU sed
at least, you can change the 1
to 0
and that works OK.
printf "%s\n" pattern pattern pattern pattern |
sed -e '0,/pattern/{s/pattern/replace/;}'
However, the description says "in the first 100 lines" and while line 1 is in the first 100 lines, that isn't the way you'd normally describe it when it appears on line 1.
You can add a -i
option to overwrite the original file once you've tested it. Beware: not all versions of sed
support -i
and on Mac OS X, the backup suffix is mandatory -i.bak
(but can be empty: use -i ''
). By contrast, GNU sed
has an optional suffix which must be attached to the -i
option. Hence, -i.bak
works with both GNU and Mac (BSD) sed
; other uses of the -i
option are specific to the variant of sed
you're using.