庆典:按列分割输出命令 [英] bash: split output of command by columns
问题描述
我想这样做:
- 运行命令
- 捕获输出
- 选择一个行
- 选择该行 的列
只是作为一个例子,让我们说,我想从 $ PID
(请注意,这只是一个例子,我不建议这是获得命令的名字从进程ID得到命令名最简单的方法 - 我真正的问题是与其他命令的输出格式,我无法控制)
Just as an example, let's say I want to get the command name from a $PID
(please note this is just an example, I'm not suggesting this is the easiest way to get a command name from a process id - my real problem is with another command whose output format I can't control).
如果我跑 PS
我得到:
PID TTY TIME CMD
11383 pts/1 00:00:00 bash
11771 pts/1 00:00:00 ps
现在我 PS | egrep的11383
并获得
11383 pts/1 00:00:00 bash
下一步: PS | egrep的11383 |切-d-f 4
。输出是:
<absolutely nothing/>
问题是,削减
削减单个空格输出,并为 PS
添加第二之间的一些空间和第3列保持表的一些相似之处,剪切
拿起一个空字符串。当然,我可以使用剪切
来选择第7,而不是第4场,但我怎么能知道,特别是当输出是可变的和未知的事先。
The problem is that cut
cuts the output by single spaces, and as ps
adds some spaces between the 2nd and 3rd columns to keep some resemblance of a table, cut
picks an empty string. Of course, I could use cut
to select the 7th and not the 4th field, but how can I know, specially when the output is variable and unknown on beforehand.
推荐答案
一个简单的方法是添加的通的 TR
挤任何重复字段分隔出来:
One easy way is to add a pass of tr
to squeeze any repeated field separators out:
$ ps | egrep 11383 | tr -s ' ' | cut -d ' ' -f 4
这篇关于庆典:按列分割输出命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!