How to write a simple Awk script to parse the output of the ps command
If you want to extract PID
(column 1 of ps
output) you can do:
ps | awk '{print $1}'
not sure what you are trying to do, but in its simplest case, awk will split on whitespace into strings you can reference via $. here's an example:
ps -ef | awk '{print $1 $2 }'
$1 is the first token, $2 is the second, etc.
What @codaddict said, but it's interesting to know also that $0 is useful if you need the whole line.
Try reading ps manual first. (either google 'man ps' or type it in a terminal)
You can customize output of ps
command and that usually mean you won't need awk
to extract data.
Your question wasn't very specific, but here's how you would use a simple Awk one liner to parse for the user name:
ps aux | awk '$1~/pratik/'
And here's how you would find jobs with PIDs greater than 14000
ps aux | awk '$2>14000'
These examples just print the results that satisfy the conditional.
$0 is the entire line string
$1 is the user name when calling ps aux
$2 is the PID
...
and so on...
To do a more complex action, after the conditional, but before the closing tick put statements inside {}. Arithmetic and other statements can be executed this way.
To turn this into a script, make a file ps_username.awk:
#!/bin/awk -f
/jmick/ {
print
}
and call something like :
ps aux |awk -f ps_username.awk
The awk script needs info to work with so here we're piping the output of ps aux
into it.
Edit: As Dennis pointed there was no need for a temporary file in my original command.