2

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....

1
  • 1
    Thanks guys, it worked Commented Apr 6, 2016 at 14:31

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

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

Comments

1

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).

2 Comments

perhaps ...{a[$8]++} END{for(k in a) ...
@karafka yup, just like anubhava's solution. I missed out on that part, but that's how I'd do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.