使用Bash按列划分命令输出? [英] Split output of command by columns using Bash?
问题描述
我想这样做:
- 运行命令
- 捕获输出
- 选择一行
- 选择该行的一列
仅作为示例,假设我想从$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
,我会得到:
If I run ps
I get:
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 | cut -d" " -f 4
.输出为:
<absolutely nothing/>
问题在于cut
将输出剪切单个空格,并且ps
在第二和第三列之间添加了一些空格以保持与表的相似性,cut
选择了一个空字符串.当然,我可以使用cut
选择第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
这篇关于使用Bash按列划分命令输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!