Reputation: 31
I am trying to write a script that would print the CPU utilisation and memory utilisation result to a csv file. But I would like to only print the values that lie in the specific columns named "CPU", "USERNAME" and "MEMORY".
Could you kindly tell me how can I achieve the same using awk script?Using awk, I have found that awk'{print $2,$5}' prints the values of the 2nd and 5th column. But I would like to print the values by providing the column name instead of the column number.
Is it possible to do that?
The sample script I have written is:
#!/bin/sh
#This is a comment
#This is my first shell script
echo "System Status Report"
date
echo "CPU Utilisation Report"
prstat -a > CPU.xls
The sample output is:
PID USERNAME SIZE RSS STATE PRI NICE TIME CPU PROCESS/NLWP
26652 root 22M 9648K sleep 1 0 94:34.26 0.2% gpp/1
26854 root 708M 697M sleep 3 0 36:23.19 0.1% logscan/1
25167 oracle 1254M 1225M sleep 1 0 14:07.01 0.0% oracle/10
NPROC USERNAME SIZE RSS MEMORY TIME CPU
41 root 1000M 834M 1.1% 143:47.47 0.4%
60 oracle 72G 70G 99% 65:07.13 0.1%
I would like to get the following output in the file:
USERNAME CPU
root 0.2%
root 0.1%
oracle 0.0%
USERNAME MEMORY
root 1.1%
oracle 99%
Upvotes: 0
Views: 1855
Reputation: 2270
Yes, definitely. This is the solution you can implement.
Say temp.tmp
is the file that contains the data.
# cat temp.tmp
Sno CPU USERNAME
1 50 foo
2 60 bar
3 65 foobar
t.awk has the awk code
# cat t.awk
NR==1 {
for (i=1; i<=NF; i++) {
ix[$i] = i
}
}
NR>1 {
print $ix[c1], $ix[c2]
}
Now lets see if it works.
# awk -f t.awk c1=CPU c2=USERNAME temp.tmp
50 foo
60 bar
65 foobar
I think this is what you want isn't it ?
Upvotes: 1