将Perl兼容的正则表达式与GNU grep -P一起使用


10

我在(?<=\[')[^,]*包含以下行的文件上使用此正则表达式disk = ['OVS/sdasd/asdasd/asdasd/something.img, w']

我希望那回来 OVS/sdasd/asdasd/asdasd/something.img

我如何使用grep它来使其工作?

我试过了,grep -P "(?<=\[')[^,]*"但它返回了整行。

Answers:


14

添加-o开关,以便grep仅返回与您要提取的模式匹配的内容:

$ grep -Po "(?<=\[')[^,]*" data.txt 
OVS/sdasd/asdasd/asdasd/something.img

6

您也可以在sed没有环视断言的情况下使用,以提高可移植性(-o可能不适用于grep):

sed "s!['\(\[^,\]*\),.*\$!\1!;t;d;p" data.txt

注意这里的反斜杠转义符的“奇怪”用法。这是由于sed默认情况下使用BRE(请参阅此问题)。

说到可移植性,为什么不只使用Perl?

perl -nle "print \$1 if /\['([^,]*)/" data.txt

2

@slm已经给您了规范的答案。这里还有其他一些选择:

使用awk'作为字段分隔符(假设所有行的格式都相同):

$ awk -F "'" '($1~/ = /){print $2}'
OVS/sdasd/asdasd/asdasd/something.img, w    

在perl中做整个事情:

$ perl -lne 'print $1 if /\[.(.*?).\]/' data.txt 
OVS/sdasd/asdasd/asdasd/something.img, w    

使用更简单的正则表达式并解析结果:

$ grep "\[.*\]" data.txt | awk -F "'" '{print $2}'
OVS/sdasd/asdasd/asdasd/something.img, w
$ grep -o "\[.*\]" data.txt | perl -pe "s/[\[\]']//g"
OVS/sdasd/asdasd/asdasd/something.img, w
$ grep "\[.*\]" data.txt | sed 's/.*\[.\(.*\).\]/\1/'
OVS/sdasd/asdasd/asdasd/something.img, w
$ grep "\[.*\]" data.txt | perl -pne 's/.*\[.(.*?).\].*/$1/'
OVS/sdasd/asdasd/asdasd/something.img, w
$ grep "\[.*\]" data.txt | perl -lne 'print $1 if /\[.(.*?).\]/'
OVS/sdasd/asdasd/asdasd/something.img, w
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.