在 Linux 上,如何確定進程標題中任意位置具有確切字串「test test 123」的進程數?

在 Linux 上,如何確定進程標題中任意位置具有確切字串「test test 123」的進程數?

我已經在 Windows 上解決了這個問題,但如何在 Linux 上做到這一點卻讓我感到困惑:

tasklist /V /NH | find "test test 123"

然後我計算輸出中非空白行的數量。這非常慢但是有效。現在我正在尋找做同樣事情的 Linux 方法。

也就是說,「test test 123」可以是完整的流程標題,可以以此開始,可以以它結束,或只是將其放在中間。這個很重要。

答案1

長話短說: 使用pgrep -cf "test test 123"


ps程式將列出所有正在運行的進程。具體來說,嘗試:

ps aux 

現在,您可以使用grep搜尋字串來過濾該列表:

ps aux | grep "test test 123"

這將列印出匹配的行。若要對它們進行計數,請使用grep -cwhich 列印出相符的行數:

ps aux | grep -c "test test 123"

這種方法的問題是grep上面的過程也會出現在結果中。例如,我目前正在編輯一個名為 的文件test test 123,但是如果我運行上面的命令,我將看到文件編輯器的進程及其grep本身:

$ ps aux | grep  "test test 123"
terdon   2461453 22.0  0.2 392944 79796 pts/1    Sl   15:53   0:02 emacs test test 123
terdon   2462354  0.0  0.0   8832  2292 pts/1    S+   15:53   0:00 grep --color test test 123

因此,grep -c將返回2而不是1

$ ps aux | grep -c "test test 123"
2

這為我們帶來了適合這項工作的工具,pgrep.這是專門為尋找進程而設計的工具:

$ pgrep -cf "test test 123"
1

意思-c是“計算匹配項”,-f意思是“搜尋整個命令行,而不僅僅是進程名稱”。

跳過grep自身的另一個常見技巧是使用單字元類別而不是相同的字串,以便grep列不會包含該字串:

$ ps aux | grep  "test test 123"
terdon   2461453  1.2  0.2 392944 79796 pts/1    Sl   15:53   0:02 emacs test test 123
terdon   2476971  0.0  0.0   8832  2236 pts/1    S+   15:56   0:00 grep --color test test 123
$ ps aux | grep  "[t]est test 123"
terdon   2461453  1.2  0.2 392944 79796 pts/1    Sl   15:53   0:02 emacs test test 123
$ ps aux | grep -c "[t]est test 123"
1

有關此技巧的更多信息,請參閱這裡。但如果您的系統具有pgrep像Linux 系統那樣的功能,則實際上沒有必要。

答案2

echo $(( $(ps aux | grep "test test 123" | wc -l) - 1))

應該有竅門

相關內容