3
[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 ?

6

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.

| improve this answer | |
  • Would be convenient for cut to have a wildcard space argument... ( I.E. cut -d '\s*' ) – Eddie B Apr 27 '17 at 14:24
  • 1
    @EddieB, you use tr for that tr -s '[[:space:]]' '[\t*]' | cut ... or use awk. – Stéphane Chazelas Apr 27 '17 at 14:31
3

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.

| 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. – Bratchley 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) – Stéphane Chazelas Apr 9 '13 at 23:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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