Manolete
Manolete

Reputation: 3517

Escape sequence even if pattern not found

I have been happily using the following code to get data out of my files

for i in 16 32 64
do
   size=$i
   printf "%d " ${size}
   awk -v pat="$size" '$0 ~ pat {printf "%f \n",$5}' $file
done

however I've noticed that if $5 is not found \n is not printed and I would like to have an escape sequence even if $5 is not found. An input example would be

 #bytes #repetitions  t_min[usec]  t_max[usec]  t_avg[usec]
            0         1000         0.04         0.09         0.06
            1         1000         0.15         1.22         0.47
            2         1000         0.16         1.25         0.49
            4         1000         0.16         1.25         0.47
            8         1000         0.16         1.30         0.49
           16         1000         0.16         1.33         0.51
           32         1000         0.17         1.40         0.53
           64         1000         0.19         1.43         0.54
          128         1000         0.18         1.56         0.59
          256         1000         0.27         1.72         0.68
          512         1000         0.25         1.91         0.73
         1024         1000         0.32         2.53         0.90
         2048         1000         0.38         3.98         1.42

An output example when $5 is found looks like:

16 0.51
32 0.53
64 0.54

if one of the values in $5 is not present (32 for instance), I would like to see

16 0.51
32 
64 0.54

Upvotes: 1

Views: 74

Answers (1)

Ed Morton
Ed Morton

Reputation: 203995

Keep it simple, efficient, and robust - throw away your shell loop and just use:

awk -v r='16 32 64' '
BEGIN {
    split(r,tmp)
    for (i in tmp) {
        reps[tmp[i]]
    }
}
$1 in reps { print $1, $5 }
' "$file"

Upvotes: 1

Related Questions