Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sed 查找并替换跨行的通配符?_Sed_Grep_Wildcard_Line Breaks_Pcregrep - Fatal编程技术网

Sed 查找并替换跨行的通配符?

Sed 查找并替换跨行的通配符?,sed,grep,wildcard,line-breaks,pcregrep,Sed,Grep,Wildcard,Line Breaks,Pcregrep,我想输入一些如下文本: foo stuff various stuff could be anything here variable number of lines bar Stuff I want to keep More stuff I want to Keep These line breaks are important 把这个拿出来: foo teststuff bar Stuff I want to keep More stuff I want to Keep The

我想输入一些如下文本:

foo
stuff
various stuff
could be anything here
variable number of lines
bar
Stuff I want to keep
More stuff I want to Keep
These line breaks are important
把这个拿出来:

 foo
 teststuff
 bar
 Stuff I want to keep
 More stuff I want to Keep
 These line breaks are important
到目前为止,我已经阅读了使用sed、grep和pcregrep的文章,但都没有成功。看起来我可能可以用Vim做这样的事情,但是我以前从来没有用过Vim,它看起来像是一种皇家的痛苦

我试过的东西包括:

sed -e s/foo.*bar/teststuff/g -i file.txt

我不确定是因为我没有正确使用这些命令,还是使用了错误的工具。我很难相信,没有办法使用终端来查找和替换跨行的通配符。

使用GNU-sed尝试以下方法:

sed -e '/^foo/,/^bar/{/^foo/b;/^bar/{i teststuff' -e 'b};d}'

请参阅:
man sed

为了软件的清晰性、简单性、健壮性、可维护性、可移植性和其他最理想的品质,只需使用awk:

$ awk 'f&&/bar/{print "teststuff";f=0} !f; /foo/{f=1}' file
foo
teststuff
bar
Stuff I want to keep
More stuff I want to Keep
These line breaks are important
这可能适用于您(GNU-sed):

这将用
teststuff
替换
foo
bar
之间的所有内容

然而,您似乎想要的是
foo
之后
bar
之前的所有内容,也许:

sed '/foo/,/bar/cfoo\nteststuff\nbar' file

是的,很有效,谢谢。我很确定我不会从手册页上看出这一点。由于某些原因,Sed对我来说似乎特别神秘……但是,当有更多的文本出现在带有foo和bar的行中时,它就不起作用了。将相同的代码与
foo和更多内容一起使用不同的内容不同的行数和一个条形内容我想保留更多的内容我想保留这些换行符是很重要的
给出了以下信息:
foo和更多内容
是否有一些通用方法可以在sed中设置一个通配符,以查找任何内容和内容两个指定字符串之间的所有内容?如果需要,我可以重新提问,因为我创建的示例似乎不够通用。请开始一个新问题。非常感谢。
sed '/foo/,/bar/cteststuff' file
sed '/foo/,/bar/cfoo\nteststuff\nbar' file