How to grep for contents after pattern?

前端 未结 7 834
礼貌的吻别
礼貌的吻别 2020-11-22 07:37

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

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 08:16

    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.

提交回复
热议问题