[英]Parse string with bash and extract number
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. 我需要提取nginx的PID。 I've done it via grep -P command, but on remote machine grep is build without perl regular expression support.
我已经通过grep -P命令完成了此操作,但是在远程计算机上grep的构建没有perl正则表达式支持。
Looks like sed or awk is exactly what I need, but I don't familiar with them. 看起来sed或awk正是我所需要的,但我并不熟悉它们。
Please help me to find a way how to do it, thanks in advance. 在此先感谢您帮助我找到一种方法。
sed 's/.*pid \([0-9]*\).*/\1/'
单独使用AWK:
awk -F'[ ,]+' '{print $4}' inputfile
Solution with awk and cut 用awk和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: 仅适用于Nginx:
vinko@parrot:~$ grep nginx test | awk '{print $4}' | cut -d, -f 1
16651
$ cat $your_output | sed -s 's/.*pid \([0-9]\+\),.*/\1/'
16652
16651
16607
看一下pgrep ,它是grep的一个特殊变体,专门用于grepping进程表。
assuming that the grep implementation supports the -o
option, you could use two greps: 假设grep实现支持
-o
选项,则可以使用两次:
output \
| grep -o '^nginx[[:space:]]\+[[:upper:]]\+[[:space:]]\+pid [0-9]\+' \
| grep -o '[0-9]\+$'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.