The POSIX-specified file editor, ex
, is capable of doing exactly that.
printf '%s\n' '/1//4/s//8/' x | ex file.txt
ex
is capable of combining multiple addresses. So /1/
means "Go to" (or refer to) "the next line matching regex 1
." Then /4/
goes from that line to the next line matching 4
. And s//8/
has the usual meaning; as in Sed, a blank regex passed to the s
command means "reuse last regex used" which in this case is 4
.
To print the modified file but not save the changes, use the following command instead:
printf '%s\n' '/1//4/s//8/' %p | ex file.txt
Just to give the idea of multiple addresses better, the following command deletes the first line containing cherry
before the first line containing banana
after line 27:
printf '%s\n' '27/banana/?cherry?d' x | ex file.txt
x
means to save changes and exit, and %p
means "print whole file." (%
is a synonym for 1,$
, which is an address range from the first line to the last line.)
sed "/4/8/" file
that's all /foo/ s/bar/foo/ means on line with foo .... substitute.... – francois P Jan 22 '18 at 21:291
further down which is followed by another4
? Do you need to replace only the 1st4
in the file which occurs after a1
or do you need to repeat that for each 1st4
that follows after a1
? – don_crissti Jan 22 '18 at 21:36awk
solution? – RomanPerekhrest Jan 22 '18 at 21:49