I want to do this:
Just as an example, l
I think the simplest way is to use awk. Example:
$ echo "11383 pts/1 00:00:00 bash" | awk '{ print $4; }'
bash
Similar to brianegge's awk solution, here is the Perl equivalent:
ps | egrep 11383 | perl -lane 'print $F[3]'
-a
enables autosplit mode, which populates the @F
array with the column data.
Use -F,
if your data is comma-delimited, rather than space-delimited.
Field 3 is printed since Perl starts counting from 0 rather than 1
Bash's set
will parse all output into position parameters.
For instance, with set $(free -h)
command, echo $7
will show "Mem:"
try
ps |&
while read -p first second third fourth etc ; do
if [[ $first == '11383' ]]
then
echo got: $fourth
fi
done
Your command
ps | egrep 11383 | cut -d" " -f 4
misses a tr -s
to squeeze spaces, as unwind explains in his answer.
However, you maybe want to use awk
, since it handles all of these actions in a single command:
ps | awk '/11383/ {print $4}'
This prints the 4th column in those lines containing 11383
. If you want this to match 11383
if it appears in the beginning of the line, then you can say ps | awk '/^11383/ {print $4}'
.
Instead of doing all these greps and stuff, I'd advise you to use ps capabilities of changing output format.
ps -o cmd= -p 12345
You get the cmmand line of a process with the pid specified and nothing else.
This is POSIX-conformant and may be thus considered portable.