带连续行的 grep

带连续行的 grep

grep//我如何awksed文件中查找某种模式,并打印整行(如果匹配的行以 结尾,则包括后续行\

文件foo.txt包含:

something
whatever
thisXXX line \
    has a continuation line
blahblah
a \
multipleXXX \
continuation \
line

我应该执行什么来获取(不一定在一行中,不一定删除多个空格):

thisXXX line has a continuation line
a multipleXXX continuation line

顺便说一句,我使用的是 bash 和 fedora21,所以它不需要符合 POSIX 标准(但如果它是 POSIX 的,我将不胜感激)

答案1

另一种使用 perl 删除前面带有\和 空格的换行符的方法:

$ perl -pe 's/\\\n/ /' file | grep XXX
thisXXX line      has a continuation line
a  multipleXXX  continuation  line

要删除多余的空格,请通过 sed 传递它:

$ perl -pe 's/\\\n/ /' file | grep XXX | sed 's/  */ /g'
thisXXX line has a continuation line
a multipleXXX continuation line

答案2

使用 POSIX sed:

$ sed -e '
:1
/\\$/{N
  s/\n//              
  t1
}
/\\/!d 
s/\\[[:blank:]]*//g
' file

答案3

pcregrep不改变线路结构的情况下:

pcregrep -M '^(.|\\\n)*XXX(.|\n)*?[^\\]$' file

答案4

我的转折:

perl -0777 -ne '                           # read the entire file into $_
    s{ [[:blank:]]* \\ \n [[:blank:]]* }   # join continued lines
     { }gx;
    print grep {/XXX/} split /(?<=\n)/     # print the matching lines
' foo.txt 
thisXXX line has a continuation line
a multipleXXX continuation line

相关内容