Sasee
Sasee

Reputation: 47

Bash script need array values in for loop

i have array values as below and used in below for loop.

a=(400 402 403 404)

for i in "${a[@]}"
do
echo $i;
done

output

400
402
403
404

I need to take array values one by one and use as below.

for i in "${a[@]}"
do
awk '{if($8==$i) print} filename.log | wc -l;
done

i need find the errors count in httpderror.log so i am passing http error codes one by one to check file and print count of error found in each http code. Http error found in 8th column ($8==$i).

output should be error count of matched lines like 400 - 44, 402 -43 but need only values as below..

 44
 43
 42 

Please help me how to do this....

Upvotes: 2

Views: 49

Answers (3)

anubhava
anubhava

Reputation: 785196

You can do this:

for i in "${a[@]}"
do
   awk -v code="$i" '$8==code{c++} END{print code, "-", c}' filename.log
done

However I suggest doing it directly in awk and avoid invoking awk command for every element in array.

awk 'BEGIN {
   a[400]=a[402]=a[403]=a[404]=0
}
$8 in a {
   a[$8]++
}
END { 
   for (i in a)
      print i, "-", a[i]
}' filename.log

Upvotes: 5

Henk Langeveld
Henk Langeveld

Reputation: 8446

Mixing data structures between two separate scripting languages is asking for trouble.

Based on the original question, you want exact matches for 400,402,403, and 404 in column 8.

Using regular expressions, you can do this in alone.

awk '$8 ~ /^40[0234]$/ {n++} END {print n}' filename.log

A shorter version would be:

awk '$8 ~ /^40[0234]$/' filename.log | wc -l

(but awk can do the counting just as well).

Upvotes: 1

Munir
Munir

Reputation: 3612

Try this:

for i in "${a[@]}"
do
    awk '{print $8}' filename.log | grep $i | wc -l
done

Upvotes: 1

Related Questions