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

2

2 Answers 2

7

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.

2
  • Would be convenient for cut to have a wildcard space argument... ( I.E. cut -d '\s*' ) Apr 27, 2017 at 14:24
  • 1
    @EddieB, you use tr for that tr -s '[[:space:]]' '[\t*]' | cut ... or use awk. Apr 27, 2017 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.

2
  • 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, 2013 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) Apr 9, 2013 at 23:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .