簡體   English   中英

限制grep的輸出

[英]Limit grep's output

我正在嘗試制作服務器管理器,但是我需要獲取某些進程的進程ID和命令。

例如:

 ps ax | grep ./skulltag
 4760 pts/2    Tl     0:02 ./skulltag-server
 4793 pts/2    Tl     0:01 ./skulltag-server
 4956 pts/2    Tl     0:01 ./skulltag-server -port 13000
 4958 pts/2    Tl     0:26 ./skulltag-server -port 13001

我如何才能僅返回進程,僅返回命令(./skulltag-server)還是同時返回兩者? 謝謝。

您可以通過管道傳輸到awk以選擇要輸出的字段

例如ps ax | grep ./skulltag | awk '{ print $1 }' ps ax | grep ./skulltag | awk '{ print $1 }' ps ax | grep ./skulltag | awk '{ print $1 }'將打印第一列(pid)

請注意,您可能還想研究使用ps的-o選項來修改其輸出

我認為你應該使用awk

ps ax | grep ./skulltag | awk '{print $1}'  # Or $5, or $1 and $5

這將為您提供進程ID的列表。

為了獲取進程ID,您還可以使用非標准但方便的pgrep

ps ax | grep ./skulltag | awk '{ print $1 }'

大致相當於:

pgrep skulltag

您可以使用awk解析ps ax的結果以提取所需的列:

aix@aix:~/tmp$ ps ax | grep bash
 1906 pts/5    Ss+    0:00 bash
13749 pts/31   Ss     0:00 bash
27315 ?        SN     0:00 /bin/bash /etc/cron.daily/backup
27648 pts/31   S+     0:00 grep --color=auto bash

aix@aix:~/tmp$ ps ax | grep bash | awk '{print $1}'
1906
13749
27315
27652

aix@aix:~/tmp$ ps ax | grep bash | awk '{print $5}'
bash
bash
/bin/bash
grep

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM