使用Bash按列划分命令输出? [英] Split output of command by columns using Bash?

查看:48
本文介绍了使用Bash按列划分命令输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做:

  1. 运行命令
  2. 捕获输出
  3. 选择一行
  4. 选择该行的一列

仅作为示例,假设我想从$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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆