Reputation: 13
I'm attempting to write output from ps
into two comma-separated columns with custom headers which I can write to a csv file. The target format looks like:
Process ID,Command name
282,sort
280,ps
284,head
136,bash
283,awk
281,awk
Here's the command I've composed so far:
ps -o pid="Process ID" -o comm="Command name" | (read -r; printf "%s\n" "$REPLY"; sort -k2 -r)
which produces the following output:
Process ID Command name
23104 sort
24756 ps
24757 bash
19320 bash
23103 awk
I need to replace the whitespace characters in each line (except the first, which needs special processing) with commas. Is there a way to do said replacement in the printf
command? Or am I approaching this wrong?
Upvotes: 1
Views: 1391
Reputation: 7499
ps -o pid,comm --no-headers | awk 'BEGIN{print "Process ID,Command name"}{$1=$1}1' OFS=,
You can use the printf
read
combo. However, in your code, the printf
prints only the first line read by read
. The rest is printed by sort
. while
loop is your friend here:
printf 'Process ID,Command name\n'
while read -r id cmd; do
printf '%s,%s\n' "$id" "$cmd"
done < <(ps -o pid,comm --no-headers)
And to have the output of ps
sorted, pipe it to sort
like you did, or use the --sort
option:
ps -o pid,comm --no-headers --sort -comm
Upvotes: 1