如何在模式后grep内容?

Lex*_*con 70 linux grep

给定一个文件,例如:

potato: 1234
apple: 5678
potato: 5432
grape: 4567
banana: 5432
sushi: 56789
Run Code Online (Sandbox Code Playgroud)

我想grep所有开头的行,potato:但只管道后面的数字potato:.所以在上面的例子中,输出将是:

1234
5432
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

rid*_*rid 99

grep 'potato:' file.txt | sed 's/^.*: //'
Run Code Online (Sandbox Code Playgroud)

要么

grep 'potato:' file.txt | cut -d\   -f2
Run Code Online (Sandbox Code Playgroud)

要么

grep 'potato:' file.txt | awk '{print $2}'
Run Code Online (Sandbox Code Playgroud)

要么

grep 'potato:' file.txt | perl -e 'for(<>){s/^.*: //;print}'
Run Code Online (Sandbox Code Playgroud)

要么

awk '{if(/potato:/) print $2}' < file.txt
Run Code Online (Sandbox Code Playgroud)

要么

perl -e 'for(<>){/potato:/ && s/^.*: // && print}' < file.txt
Run Code Online (Sandbox Code Playgroud)

  • 这些变种需要一些解释 (5认同)
  • 不需要两个进程和一个管道.我会去'awk'$ 1~/potato/{print $ 2}'file.txt`. (2认同)
  • awk 更惯用的是`awk '/potato:/ {print $2}'` (2认同)

moh*_*6up 57

或者使用正则表达式断言: grep -oP '(?<=potato: ).*' file.txt

  • 我从上面接受的答案中尝试了一些单行,但我觉得这个答案更准确地解决了这个问题. (4认同)
  • 一些解释:选项`-o`表示只打印该行的匹配部分.而`-P`推断出与Perl兼容的正则表达式,恰好是[正向lookbehind](http://www.regular-expressions.info/lookaround.html)正则表达式(?<= string)`. (3认同)
  • **注意**:由于 `-P` 选项,此解决方案仅与 [GNU `grep`](https://www.gnu.org/software/grep/) 兼容,不适用于您可以在 macOS 等环境中找到这种 [POSIX `grep`](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/grep.html)。 (2认同)

thb*_*thb 9

sed -n 's/^potato:[[:space:]]*//p' file.txt
Run Code Online (Sandbox Code Playgroud)

人们可以将Grep视为限制性Sed,或将Sed视为广义Grep.在这种情况下,Sed是一个很好的轻量级工具,可以满足您的需求 - 当然,还有其他一些合理的方法可以实现.


tux*_*tku 7

grep -Po 'potato:\s\K.*' file
Run Code Online (Sandbox Code Playgroud)

-P 使用 Perl 正则表达式

-o 只输出匹配

\s 匹配后的空间 potato:

\K 省略比赛

.* 匹配其余的字符串

  • **注意**:由于 `-P` 选项,此解决方案仅与 [GNU `grep`](https://www.gnu.org/software/grep/) 兼容,不适用于您可以在 macOS 等环境中找到这种 [POSIX `grep`](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/grep.html)。 (4认同)