在特定单词后获取值

use*_*375 9 shell string

我有这个文件

1 deiauk David Smith from California 12 58
2 edvin from Nevada 12 5 8 95 2 48 5
3 jaco My Name Is Jacob I'm from NY 5  6  845 156 585
4 from Miami
Run Code Online (Sandbox Code Playgroud)

我需要在特定单词之后获取值from是否可以在 shell 中执行此操作?我的输出应该是

California
Nevada
NY
Miami
Run Code Online (Sandbox Code Playgroud)

shi*_*ams 20

使用grep,可以按如下方式完成:

grep -oP "from\s+\K\w+" input.txt
Run Code Online (Sandbox Code Playgroud)

这里,

-o  ==>  option for printing only the matching part of the line
-P  ==>  use perl-regexp
\K  ==>  do not print that comes before \K (zero-width look-behind assertion)
\w  ==>  match word characters
Run Code Online (Sandbox Code Playgroud)


小智 11

或者:

awk '{for (I=1;I<NF;I++) if ($I == "from") print $(I+1)}' file
Run Code Online (Sandbox Code Playgroud)


Jig*_*rji 7

一个可读的解决方案是:

awk -F '${fixed_string}' '{print $2}' file | awk '{print $1}'
Run Code Online (Sandbox Code Playgroud)

它能做什么:

  • -F '${fixed_string}'将输入分成给定字符串之前和之后。因此,对于您的文件,当我们设置时fixed_string='from'print $2会给出:

    California 12 58 Nevada 12 5 8 95 2 48 5 NY 5 6 845 156 585 Miami

  • 现在,您只需要此输入的第一列。因此,我们将第一列的输出通过管道awk传输到awk并打印第一列。