简体   繁体   English

如何使用grep从文件中检索匹配的文本?

[英]How to use grep to retrieve matching text from a file?

I have a txt file like this: 我有一个这样的txt文件:

asdfasdf
ffaCover 91adf
ffffa

I want to use grep or some linux tool to capture the 1 or 2 digits following the space after 'Cover'. 我想使用grep或一些linux工具来捕获'Cover'之后空格后的1或2位数。 In some programming languages I would use the regex library to match /^Cover (\\d\\d?)$/. 在某些编程语言中,我会使用正则表达式库匹配/ ^ Cover(\\ d \\ d?)$ /。 Then there would be some way to get at the 1 or 2 digits inside the parenthesis. 然后会有一些方法来获得括号内的1或2位数。 Is there a way to do this using grep? 有没有办法用grep做到这一点?

Just pipe to grep -oP : 只需管道grep -oP

grep -Po 'Cover \K[0-9]{1,2}'
91

\\K in PCRE regex resets all previously matched information. PCRE正则表达式中的\\K重置所有先前匹配的信息。

I had always done something like this: 我总是这样做:

 grep -Po '(?<=Cover\s)(\d\d?)'

The -o option to grep makes it print out only the matching part of the pattern, which does not include the zero-width lookbehind assertion. grep-o选项使其仅打印出模式的匹配部分,其中不包括零宽度lookbehind断言。

But, I did not know about the \\K option in anubhava's answer before, which seems cleaner. 但是,我之前不知道anubhava的答案中的\\K选项,这似乎更清晰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM