Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split output of command by columns using Bash?

Tags:

linux

bash

pipe

I want to do this:

  1. run a command
  2. capture the output
  3. select a line
  4. select a column of that line

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).

If I run ps I get:

    PID TTY          TIME CMD 11383 pts/1    00:00:00 bash 11771 pts/1    00:00:00 ps  

Now I do ps | egrep 11383 and get

11383 pts/1    00:00:00 bash

Next step: ps | egrep 11383 | cut -d" " -f 4. Output is:

<absolutely nothing/> 

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.

like image 777
flybywire Avatar asked Oct 27 '09 10:10

flybywire


People also ask

Can you use && in bash?

The Bash logical (&&) operator is one of the most useful commands that can be used in multiple ways, like you can use in the conditional statement or execute multiple commands simultaneously.

How do you split a column in Unix?

A nifty command called cut lets you select a list of columns or fields from one or more files. You must specify either the -c option to cut by column or -f to cut by fields. (Fields are separated by tabs unless you specify a different field separator with -d.


1 Answers

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 
like image 134
unwind Avatar answered Oct 15 '22 00:10

unwind