How to grep for contents after pattern?

2019-01-01 07:20发布

问题:

Given a file, for example:

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

I\'d like to grep for all lines that start with potato: but only pipe the numbers that follow potato:. So in the above example, the output would be:

1234
5432

How can I do that?

回答1:

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

or

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

or

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

or

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

or

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

or

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


回答2:

Or use regex assertions: grep -oP \'(?<=potato: ).*\' file.txt



回答3:

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

One can think of Grep as a restricted Sed, or of Sed as a generalized Grep. In this case, Sed is one good, lightweight tool that does what you want -- though, of course, there exist several other reasonable ways to do it, too.



回答4:

This will print everything after each match, on that same line only:

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

This will do the same, except it will also print all subsequent lines:

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

These command-line options are used:

  • -n loop around each line of the input file
  • -l removes newlines before processing, and adds them back in afterwards
  • -e execute the perl code


回答5:

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.



标签: linux grep