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.
[root@localhost ~]#  ps aux | grep ata
root        19  0.0  0.0      0     0 ?        S    07:52   0:00 [ata/0]
root        20  0.0  0.0      0     0 ?        S    07:52   0:00 [ata_aux]
root      1655  0.0  2.6  22144 13556 tty1     Ss+  07:53   0:18 /usr/bin/Xorg :0 -nr -verbose -auth /var/run/gdm/auth-for-gdm-t1gMCU/database -nolisten tcp vt1
root      3180  0.0  0.1   4312   728 pts/0    S+   14:09   0:00 grep ata
[root@localhost ~]#  ps aux | grep ata | cut -d" " -f 2

[root@localhost ~]#

I would expect second column in the output; but not getting anything. Any ideas ?

share|improve this question
    
Here is an answer –  Vincent Nivoliers Apr 9 '13 at 13:10
1  
    
+1, for the link @don_crissti. –  Ankit Apr 9 '13 at 13:23
add comment

2 Answers

up vote 5 down vote accepted

With -d " ", the field separator is one (and only one) space character. Contrary to the shell word splitting, cut doesn't treat space any different than any other character. So cut -d " " -f2 returns "" in root   19, just like it would return "" for cut -d: -f2 in root:::19.

You'd need to either squeeze the blanks to transform any sequence of space into one space:

ps aux | grep ata | tr -s ' ' | cut -d ' ' -f2

Or use awk where in its default spitting mode, it doesn't use a separator but splits into the list of sequences of non-blank characters:

ps aux | awk '/ata/{print $2}'

In this case though, you may want to use:

pgrep -f ata

Or at least:

ps -eo pid= -o args= | awk '/ata/{print $1}'

To match against the arguments only.

share|improve this answer
add comment

Use:

ps aux | awk '/ata/{print $2}'

The cut command you are using is not giving the desired output as there are more than one space between columns.

share|improve this answer
    
FWIW, fields being separated by a variable amount of whitespace is one of the few cases where awk beats cut for regular field extraction. Cut is more useful in the general case but it doesn't handle multi-character delimiters (esp variable-length ones) very well at all. –  Joel Davis Apr 9 '13 at 14:55
    
@JoelDavis, GNU or busybox cut may not handle multibyte character delimiters but other like heirloom toolchest's or ksh93 builtin ones do. Similarly some awk implementations like mawk don't support multibyte characters very well (try mawk -F'[áóíúýé]' '{print $2}' for instance) –  Stephane Chazelas Apr 9 '13 at 23:15
add comment

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.