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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like