如何在模式后grep内容?

时间:2012-04-27 22:12:27

标签: linux grep

给定一个文件,例如:

potato: 1234
apple: 5678
potato: 5432
grape: 4567
banana: 5432
sushi: 56789

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

1234
5432

我该怎么做?

7 个答案:

答案 0 :(得分:82)

grep 'potato:' file.txt | sed 's/^.*: //'

grep 'potato:' file.txt | cut -d\   -f2

grep 'potato:' file.txt | awk '{print $2}'

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

awk '{if(/potato:/) print $2}' < file.txt

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

答案 1 :(得分:48)

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

答案 2 :(得分:8)

sed -n 's/^potato:[[:space:]]*//p' file.txt

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

答案 3 :(得分:2)

这将在每场比赛后打印所有内容,仅在同一行上打印:

perl -lne 'print $1 if /^potato:\s*(.*)/' file.txt

这样做也是如此,除了它还会打印所有后续行:

perl -lne 'if ($found){print} elsif (/^potato:\s*(.*)/){print $1; $found++}' file.txt

使用以下命令行选项:

  • -n循环输入文件的每一行
  • -l在处理之前删除换行符,然后将其添加回来
  • -e执行perl代码

答案 4 :(得分:2)

grep -Po 'potato:\s\K.*' file

-P使用Perl正则表达式

-o仅输出匹配项

\s以匹配potato:后的空格

\K忽略了比赛

.*以匹配其余字符串

答案 5 :(得分:1)

You can use grep, as the other answers state. But you don't need grep, awk, sed, perl, cut, or any external tool. You can do it with pure bash.

Try this (semicolons are there to allow you to put it all on one line):

$ while read line;
  do
    if [[ "${line%%:\ *}" == "potato" ]];
    then
      echo ${line##*:\ };
    fi;
  done< file.txt

## tells bash to delete the longest match of ": " in $line from the front.

$ while read line; do echo ${line##*:\ }; done< file.txt
1234
5678
5432
4567
5432
56789

or if you wanted the key rather than the value, %% tells bash to delete the longest match of ": " in $line from the end.

$ while read line; do echo ${line%%:\ *}; done< file.txt
potato
apple
potato
grape
banana
sushi

The substring to split on is ":\ " because the space character must be escaped with the backslash.

You can find more like these at the linux documentation project.

答案 6 :(得分:0)

现代BASH支持正则表达式:

while read -r line; do
  if [[ $line =~ ^potato:\ ([0-9]+) ]]; then
    echo "${BASH_REMATCH[1]}"
  fi
done