bash 如何处理grep中的括号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8920450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:21:31  来源:igfitidea点击:

How to handle parenthesis in grep?

bashgrep

提问by Misha Moroshko

stris of the following pattern:

str是以下模式:

1 abc (1 <something>)

For example:

例如:

1 abc (1 hello)
1 abc (1 shalom)
1 abc (1 hola)

How could I extract <something>from strusing egrep?

我怎么<something>能从strusing 中提取egrep

回答by mathematical.coffee

If you want to extract just the <something>then I'd suggest grep -P(perl regex):

如果你只想提取<something>然后我建议grep -P(perl regex):

grep -P -o '(?<=\(1 ).*?(?=\))' INPUTFILE

The -oreturns just the matched portion being <something>. The regex looks for text preceded by (1and followed by ).

-o返回刚刚匹配部分是<something>。正则表达式查找前面(1和后面的文本)

You wouldn't be able to do that with egrepas it doesn't support lookarounds. The best you'd do is extract the (1 <something>)with:

您将无法做到这一点,egrep因为它不支持环视。你最好做的是提取(1 <something>)

egrep -o '\(1 (.*)\)' INPUTFILE

[foo@bar ~]$ grep -P -o '(?<=\(1 ).*?(?=\))' INPUTFILE
hello
shalom
hola

[foo@bar ~]$ egrep -o '\(1 (.*)\)' INPUTFILE
(1 hello)
(1 shalom)
(1 hola)

回答by jaypal singh

Alternatively you can use a simple awkone-liner for this.

或者,您可以awk为此使用简单的单衬。

awk -F"[ )]" '{print $(NF-1)}' filename

Test:

测试:

[jaypal:~/Temp] cat filename
1 abc (1 hello)
1 abc (1 shalom)
1 abc (1 hola)

[jaypal:~/Temp] awk -F"[ )]" '{print $(NF-1)}' filename
hello
shalom
hola