使用 bash ps 并切到一起
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15643834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using bash ps and cut together
提问by darxsys
I need to extract PID, UID and command fields from 'ps' and I have tried it like this:
我需要从 'ps' 中提取 PID、UID 和命令字段,我试过这样的:
ps -L u n | cut -f 1,2,13
ps -L u n | cut -f 1,2,13
For some reason, this behaves as there is no cut command whatsoever. It just returns normal ps output. Then, I tried
出于某种原因,这表现为没有任何剪切命令。它只是返回正常的 ps 输出。然后,我试过了
ps -L u n | tr -s " " | cut -d " " -f 1,2,13
and this returns total nonsense. Then, I tried playing with it and with this:
ps -L u n | tr -s " " | cut -d " " -f 1,2,13
这完全是胡说八道。然后,我尝试使用它并使用它:
ps -L u n | tr -s " " | cut -d " " -f 2,3,14
ps -L u n | tr -s " " | cut -d " " -f 2,3,14
and this somehow returns what I need (almost, and I don't understand why that almost works), except that it cuts out the command field in the middle of it. How can I get what I need?
这以某种方式返回了我需要的东西(几乎,我不明白为什么这几乎有效),除了它删除了它中间的命令字段。我怎样才能得到我需要的东西?
回答by Explosion Pills
ps
is printing out space separators, but cut
without -d
uses the tab character. The tr -s
squeezes the spaces together to get more of the separation that you want, but remember that there is the initial set of spaces (squeezed to one) hence why you need to add 1 to each field. Also, there are spaces in the commands for each word. This should work:
ps
正在打印空格分隔符,但cut
不-d
使用制表符。将tr -s
空格压缩在一起以获得更多您想要的分隔,但请记住,有一组初始空格(压缩为一个),因此您需要向每个字段添加 1。此外,每个单词的命令中都有空格。这应该有效:
ps -L u n | tr -s " " | cut -d " " -f 2,3,14-
回答by Sylvain Kalache
Is there any particular reason for using cut?
使用 cut 有什么特别的原因吗?
I guess this will do what you want:
我想这会做你想做的:
ps -eopid,uid,cmd
回答by Nathan Adams
You can use awk to clean up your command, like so:
您可以使用 awk 来清理您的命令,如下所示:
ps -L u n | awk '{ print ,, }'
回答by Pat
The question is what to do once you have a list.I find cut kludgy, so instead of cutI pass the list to a while readloop. "While read" recognizes non-blank values on a line, so in this example, "a" is the first value, "b" is the second and "c" is the rest of the line. I am only interested in the first 2 values, process owner and process ID; and I basically abuse the case statement rather than use an "if". (Even though grep filtered, I don't want to kill processes where the owner name might be embedded elsewhere in the line)
问题是一旦你有了清单,该怎么做。我发现cutkludgy,所以我将列表传递给while read循环而不是cut。“While read”识别一行上的非空白值,因此在本例中,“a”是第一个值,“b”是第二个值,“c”是该行的其余部分。我只对前 2 个值感兴趣,进程所有者和进程 ID;我基本上是滥用 case 语句而不是使用“if”。(即使 grep 过滤了,我也不想杀死所有者名称可能嵌入行中其他位置的进程)
ps -ef | grep owner | grep -v grep | while read a b c;
do
case $a in
"owner")
kill -9 $b
;;
esac;
done