regex命令行linux-选择两个字符串之间的所有行
我有一个文本文件,内容如下:regex命令行linux-选择两个字符串之间的所有行,regex,linux,grep,Regex,Linux,Grep,我有一个文本文件,内容如下: here is some super text: this is text that should be selected with a cool match And this is how it all ends blah blah... grep "my regex goes here" myFileNameHere 我正在尝试获取这两条线,但这两条线之间可能会有更多或更少的线: 一些超级文本: 及 这就是为什么 我在ubuntu机器上使用grep,
here is some super text:
this is text that should
be selected with a cool match
And this is how it all ends
blah blah...
grep "my regex goes here" myFileNameHere
我正在尝试获取这两条线,但这两条线之间可能会有更多或更少的线:
一些超级文本:
及
这就是为什么
我在ubuntu机器上使用grep,我发现很多模式似乎都是针对不同类型的正则表达式引擎的
所以我应该以这样的方式结束:
here is some super text:
this is text that should
be selected with a cool match
And this is how it all ends
blah blah...
grep "my regex goes here" myFileNameHere
不确定是否需要egrep,但可以简单地使用它。您可以在sed中使用地址:
sed -e '/some super text/,/And this is how/!d' file
!!d表示如果不在范围内,则不输出
要排除边界线,您必须更聪明:
sed -n -e '/some super text/ {n;b c}; d;:c {/And this is how/ {d};p;n;b c}' file
或者,类似地,在Perl中:
perl -ne 'print if /some super text/ .. /And this is how/' file
要再次排除边界线,请将其更改为
perl -ne '$in = /some super text/ .. /And this is how/; print if $in > 1 and $in !~ /E/' file
您可以在sed中使用地址:
sed -e '/some super text/,/And this is how/!d' file
!!d表示如果不在范围内,则不输出
要排除边界线,您必须更聪明:
sed -n -e '/some super text/ {n;b c}; d;:c {/And this is how/ {d};p;n;b c}' file
或者,类似地,在Perl中:
perl -ne 'print if /some super text/ .. /And this is how/' file
要再次排除边界线,请将其更改为
perl -ne '$in = /some super text/ .. /And this is how/; print if $in > 1 and $in !~ /E/' file
我不知道如何在grep中做到这一点。使用awk:
我不知道如何在grep中做到这一点。使用awk: TL;博士 对于语料库,另一种解决问题的方法是用前导空格匹配行,而不是使用某种触发器操作符来匹配起始行和结束行。以下解决方案适用于您发布的示例 GNU Grep和PCRE在中编译 替代方法:使用pcregrep TL;博士 对于语料库,另一种解决问题的方法是用前导空格匹配行,而不是使用某种触发器操作符来匹配起始行和结束行。以下解决方案适用于您发布的示例 GNU Grep和PCRE在中编译 替代方法:使用pcregrep
试着用pcregrep代替正常的grep。因为普通grep无法帮助您获取一行中的多行
$ pcregrep -M -o '(?s)some super text:[^\n]*\n\K.*?(?=\n[^\n]*And this is how)' file
this is text that should
be selected with a cool match
?s Dotall修饰符允许点匹配甚至换行符。
\K丢弃先前匹配的字符。
来自pcregrep-帮助
试着用pcregrep代替正常的grep。因为普通grep无法帮助您获取一行中的多行
$ pcregrep -M -o '(?s)some super text:[^\n]*\n\K.*?(?=\n[^\n]*And this is how)' file
this is text that should
be selected with a cool match
?s Dotall修饰符允许点匹配甚至换行符。
\K丢弃先前匹配的字符。
来自pcregrep-帮助
这个给了我第2行和第3行,没有第1行和第4行。非常感谢。只有一个问题。在我的台词的开头和结尾都有非常奇怪的字符。e、 g.^[1m和^[0m^[37m]^[[40m@carter这些是用于设置颜色的控制台控制代码。更改生成输出的命令上的选项,使其不输出颜色代码。这一个实际上给了我第2行和第3行,没有第1行和第4行。非常感谢。只有一个问题。它在我的行的开头和结尾包含非常奇怪的字符。例如^[[1m和^[[0m^[[37m]^[[40m@carter这些是用于设置颜色的控制台控制代码。更改生成输出的命令上的选项,使其不输出颜色代码。它将不满足op的条件。它将不满足op的条件。