I am trying to write a script that will filter the command information sar
and display it in XML format.
To do this, it has occurred to me to make a loop that shows the data of each CPU and, within it, another loop that goes through the filtered fields in the variable last_time
.
My code is the following:
#Obtenemos el numero de nucleos de la CPU
NUM_CPU=$(grep processor /proc/cpuinfo | wc -l)
#Por cada nucleo, mostramos sus estadísticas
for i in $(seq 0 1 $(($NUM_CPU-1))); do
#Guardamos la última medida de sar en una variable
last_time=$(sar -P $i | tail -n 2 | head -n 1)
for j in $(seq 3 1 8); do
#Filtramos el campo correspondiente
cpu_user=$(echo $last_time | gawk '{print $j}')
#Mostramos el valor en XML
echo "<module>"
echo "<name><![CDATA[SAR: CPU$i $cpu_user]]></name>"
echo "<description>Muestra el % de tiempo de usuario de la cpu $i</description>"
echo "<type><![CDATA[generic_data]]></type>"
echo "<![CDATA[15,1]]>"
echo "</module>"
#Imprimimos una linea en blanco para separar la siguiente seccion
echo ""
done;
done;
Most of the code runs fine, but when trying to apply gawk with the variable $j
(which would indicate the number of the field to filter), gawk does not detect the value of the variable and does not filter anything
How can I solve it?
To use Bash variables in awk you must pass them to it using
-v
:If you want to use it to do comparisons at the regular expression level, you must use the operator
~
:Therefore, the line:
Would
That said, your code could be written as:
I have prefaced the suggestions with
####
. Basically it usesnproc --all
to count cores and uses one heredoc instead of manyecho
s.