[英]Use sed to Replace Multiple Lines
I'm trying to use sed to replace multiple lines which are found via regex with one substitution.我正在尝试使用 sed 将通过正则表达式找到的多行替换为一个替换。 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我 go 如何使用正则表达式查找第二到第四行并将整个范围替换为单词“找到”的一个实例,以便最终结果是
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.我基本上是想将替换语法 (
sed 's/second/found/'
) 与范围语法 ( sed '/second/,/fourth/'
) 组合成类似sed 's/second/,/fourth/found/'
东西sed 's/second/,/fourth/found/'
确实有效。
awk
suited this job better: awk
适合这份工作:
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
然后使用:
sed '/^second$/,/^fourth$/{/^second$/i\
found
d
}' file
Using sed
使用
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):这可能对你有用(GNU sed):
sed '/second/,/fourth/cfound' file
or for those line numbers:或者对于那些行号:
sed '2,4cfound' file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.