Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I would like to get the second argument in a line of output. For example:

ps aux

gives me an output that contains the cpu-usage %CPU in the third column.

How can I filter the output so I have only that column?

I tried

ps aux | cut -f 3

but that's not working

see also: Filtering the Xth element in a row?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

There's a number of ways to accomplish this. Here's an example using awk:

ps aux | awk '{print $3}'

The $3 argument to the print command will print the third field, by default delimited by a sequence of whitespace, of each line.

share|improve this answer

Using ps format options

ps allows you to specify a custom output format.

ps ax o pcpu

The above command would return a single column of CPU usage data.

Why cut doesn't work

cut's default delmiter is the tab character. ps uses spaces in its output, so you would have to use cut -d' ' -f3 to select the third field (as cut sees it).

The problem with using cut is that it views anything adjacent to a delimiter as a field. Since ps prints multiple adjacent spaces between fields,

$ ps aux
...
para␣␣␣␣␣␣␣462␣␣0.0␣␣0.0␣␣13492␣␣1792␣tty1␣␣␣␣␣Ss+␣␣05:52␣␣␣0:00
root␣␣␣␣␣␣␣484␣␣1.8␣␣0.5␣137020␣45112␣?␣␣␣␣␣␣␣␣Ss␣␣␣05:52␣␣␣0:20
para␣␣␣␣␣␣␣490␣␣0.0␣␣0.0␣␣28072␣␣1708␣tty1␣␣␣␣␣S␣␣␣␣05:52␣␣␣0:00
...
$ ps aux | cut -d' ' -f3
...
␣
␣
␣
...

cut will print a column of spaces if you ask it for the third field. To make matters worse, the number of spaces that ps outputs between each field is not always uniform among the rows, so you can't just use cut -d' ' -f12 You would end up with results like this:

...
4.6
0.0
0.0
␣
␣
0.0
0.1
␣
␣
␣
...
share|improve this answer
    
If you want to find a process in ps aux you can also use pgrep to just find the process nr. –  rubo77 Jun 13 '13 at 15:23
    
Is there no possibility to tell cut to treat multiple spaces as one delimiter? then I could imagine a solution with cut too –  rubo77 Jun 13 '13 at 15:24
    
Unfortunately, there is no way to tell cut to treat multiple spaces as one delimiter. –  paraxor Jun 13 '13 at 19:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.