Cut the Second Field Delimited by Spaces

I want to retrieve the second column from ps result:

test@pc:~$ ps -e | head -5 | cut -d '' -f1
  PID TTY          TIME CMD
    1 ?        00:00:03 systemd
    2 ?        00:00:00 kthreadd
    3 ?        00:00:00 rcu_gp
    4 ?        00:00:00 rcu_par_gp

It does not work, I learned that it could be solve the a complicated way as:

test@pc:~$ ps -e | head -5 | gawk '{print $2}'
TTY
?
?
?
?

How could solve the problem with the generic tool of cut?

1

1 Answer

First we replace each sequence of a repeated spaces using tr -s ' ' then we grab the 3th column:

ps -e | head -5 | tr -s ' ' | cut -d ' ' -f3

3th column because there is a space at the beginning of each line. We can remove that too:

ps -e | head -5 | tr -s ' ' | sed 's/ //' | cut -d ' ' -f2
1

Your Answer

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

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest