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?...
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 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