I want to use a Bash script to make summarize reading csv file. The script only reads $1, $2 and $4.
I want to use $1, $2 as a key and $4 for value but if there is a records for "critical" then print it as $1, $2, "critical" in a row. but instead of using "==", "=~" is not working on awk. and "contains" is not working properly in this time.
If anyone helps me to solve this problem, it would really be appreciated.
'''
Input
A, SVC-ID01, Critical A, SVC-ID01, Info A, SVC-ID01, Good A, SVC-ID01, Good A, SVC-ID01, Good A, SVC-ID02, Info A, SVC-ID02, Info A, SVC-ID02, Good B, SVC-ID-03, Good B, SVC-ID-03, Good B, SVC-ID-03, Good B, SVC-ID-04, Info B, SVC-ID-04, Info B, SVC-ID-04, Good B, SVC-ID-04, Info
awk -F "," '{
if (NR != 1)
arr[$1","$2];
arr2[$1","$2]=$4;
if (arr2[$1","$2] == "Critical")
{
arr2[$1","$2]="Critical";
}
else if (arr2[$1","$2] == "Info")
{
arr2[$1","$2]="Info";
}
else
{
arr2[$1","$2]="Good";
}
} END {for (i in arr) {print i "" arr[i] "," arr2[i]} }' ${filename} | sort $2
output
A, SVC-ID01, Critical A, SVC-ID02, Info B, SVC-ID-03, Good B, SVC-ID-04, Info
'''
I would use a couple of lookup tables to make "Critical" the "max" value:
awk '
BEGIN {
FS = SUBSEP = OFS = ", "
state["Good"] = 1; lookup[1] = "Good"
state["Info"] = 2; lookup[2] = "Info"
state["Critical"] = 3; lookup[3] = "Critical"
}
value[$1, $2] < state[$3] {value[$1, $2] = state[$3]}
END {
PROCINFO["sorted_in"] = "@ind_str_asc"
for (key in value) print key, lookup[value[key]]
}
' Input
This outputs
A, SVC-ID01, Critical
A, SVC-ID02, Info
B, SVC-ID-03, Good
B, SVC-ID-04, Info
You don't have 4 columns and if not Critical or Info is already set, assign $3 to the array. The field separator also looks like it should be ", " or else you'd need to match on " Critial" and " Info".
Example:
awk -F ", " '{
arr[$1", "$2];
if ($3 == "Critical" || arr2[$1", "$2] == "Critical")
{
arr2[$1", "$2]="Critical";
}
else if (arr2[$1", "$2] != "Info")
{
arr2[$1", "$2]=$3;
}
}
END {for (i in arr) {print i "" arr[i] ", " arr2[i]} }' ${filename} | sort $2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With