如何获取第二列和第二行中的数字或 return 默认值

how to get the number in second column and second row or return a default value

我被 grep 困住了,请告诉我一个正则表达式解决方案来获取第二行第二列中的数字

我只是想为侦听端口获取 pid

lsof -i:43458 |grep LISTEN

得到

skype   2680 orangehrm   85u  IPv4  17151      0t0  TCP *:43458 (LISTEN)

但据我所知,我还需要知道如何获取该行

示例数据

COMMAND  PID      USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
skype   2680 orangehrm   85u  IPv4  17151      0t0  TCP *:43458 (LISTEN)

skype   2680 orangehrm   86u  IPv4  17152      0t0  UDP *:43458 

下面的 awk 命令将打印第二列,如果,

  1. 该行必须包含字符串 LISTEN

  2. 第二列必须包含一位或多位数字

    lsof -i:43458 | awk '/LISTEN/ &&  ~ /^[0-9]+$/{print }'
    

示例:

$ cat f
foo 123 LISTEN
foo bar LISTEN
$ awk '/LISTEN/ &&  ~ /^[0-9]+$/{print }' f
123

使用tr and cut的另一个解决方案:

lsof -i:43458 | grep LISTEN | tr -s ' ' | cut -d " " -f 2

tr 用于删除单词之间任何额外的 space。 cut用于select你想要的字段(这里是第二个)。