I'm trying to use sed to replace multiple lines which are found via regex with one substitution. For example, given the following simplified text file
first
second
third
fourth
fifth
sixth
seventh
eighth
How would I go about using regex to find the second to fourth lines and replace the whole range with one instance of the word "found" so that the end result is
first
found
fifth
sixth
seventh
eighth
I'm basically looking to combine the substitution syntax ( sed 's/second/found/'
) with the range syntax ( sed '/second/,/fourth/'
) into something like sed 's/second/,/fourth/found/'
that actually works.
awk
suited this job better:
awk '/^second$/ {p=1} !p; /^fourth$/ {p=0; print "found"}' file
first
found
fifth
sixth
seventh
eighth
If you really want to use sed
then use:
sed '/^second$/,/^fourth$/{/^second$/i\
found
d
}' file
Using sed
$ sed '/second/,/third/{d};x;x;s/fourth/found/' input_file
first
found
fifth
sixth
seventh
eighth
This might work for you (GNU sed):
sed '/second/,/fourth/cfound' file
or for those line numbers:
sed '2,4cfound' file
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.