Parse string with bash and extract number

2020-03-01 08:01发布

I've got supervisor's status output, looking like this.

frontend                         RUNNING    pid 16652, uptime 2:11:17
nginx                            RUNNING    pid 16651, uptime 2:11:17
redis                            RUNNING    pid 16607, uptime 2:11:32

I need to extract nginx's PID. I've done it via grep -P command, but on remote machine grep is build without perl regular expression support.

Looks like sed or awk is exactly what I need, but I don't familiar with them.

Please help me to find a way how to do it, thanks in advance.

6条回答
等我变得足够好
2楼-- · 2020-03-01 08:08
sed 's/.*pid \([0-9]*\).*/\1/'
查看更多
三岁会撩人
3楼-- · 2020-03-01 08:11
$ cat $your_output | sed -s 's/.*pid \([0-9]\+\),.*/\1/'
16652
16651
16607
查看更多
倾城 Initia
4楼-- · 2020-03-01 08:15

Solution with awk and cut

vinko@parrot:~$ cat test
frontend                         RUNNING    pid 16652, uptime 2:11:17
nginx                            RUNNING    pid 16651, uptime 2:11:17
redis                            RUNNING    pid 16607, uptime 2:11:32
vinko@parrot:~$ awk '{print $4}' test | cut -d, -f 1
16652
16651
16607

for nginx only:

vinko@parrot:~$ grep nginx test | awk '{print $4}' | cut -d, -f 1
16651
查看更多
The star\"
5楼-- · 2020-03-01 08:24

assuming that the grep implementation supports the -o option, you could use two greps:

output \
  | grep -o '^nginx[[:space:]]\+[[:upper:]]\+[[:space:]]\+pid [0-9]\+' \
  | grep -o '[0-9]\+$'
查看更多
Root(大扎)
6楼-- · 2020-03-01 08:28

Using AWK alone:

awk -F'[ ,]+' '{print $4}' inputfile
查看更多
三岁会撩人
7楼-- · 2020-03-01 08:31

Take a look at pgrep, a variant of grep specially tailored for grepping process tabless.

查看更多
登录 后发表回答