Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using bash ps and cut together

Tags:

bash

unix

cut

ps

I need to extract PID, UID and command fields from 'ps' and I have tried it like this:

ps -L u n | cut -f 1,2,13

For some reason, this behaves as there is no cut command whatsoever. It just returns normal ps output. Then, I tried

ps -L u n | tr -s " " | cut -d " " -f 1,2,13 and this returns total nonsense. Then, I tried playing with it and with this:

ps -L u n | tr -s " " | cut -d " " -f 2,3,14

and this somehow returns what I need (almost, and I don't understand why that almost works), except that it cuts out the command field in the middle of it. How can I get what I need?

like image 776
darxsys Avatar asked Mar 26 '13 17:03

darxsys


People also ask

What is bash ps command?

The ps command, short for Process Status, is a command line utility that is used to display or view information related to the processes running in a Linux system. As we all know, Linux is a multitasking and multiprocessing system. Therefore, multiple processes can run concurrently without affecting each other.

What is cut in bash script?

The cut command is used to extract the specific portion of text in a file. Many options can be added to the command to exclude unwanted items. It is mandatory to specify an option in the command otherwise it shows an error.


1 Answers

ps is printing out space separators, but cut without -d uses the tab character. The tr -s squeezes the spaces together to get more of the separation that you want, but remember that there is the initial set of spaces (squeezed to one) hence why you need to add 1 to each field. Also, there are spaces in the commands for each word. This should work:

ps -L u n | tr -s " " | cut -d " " -f 2,3,14- 
like image 151
Explosion Pills Avatar answered Sep 27 '22 01:09

Explosion Pills