ActiveState Code

Recipe 576876: awk sample


this is an awk sample

Text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/bash

file=${1:?"file?"}

echo $*
#get the fields
#delete the non-ditital data, user, system, elapsed
#convert the real time 's min:sec
#print the fields

#awk 'BEGIN { FS = "\n"; RS = "" }\
#{print $2}' $file \
sed -n '/.*user.*system.*/p' $file \
|sed -e 's/user//' -e 's/system//' -e 's/elapsed//' |\
awk 'BEGIN { FS = " "; RS = "\n" }\
{split($3, real, ":"); $3=real[1]*60 + real[2]} \
#{printf $1 "\t"$2 "\t" $3"\n"} \
{ user_sum += $1;  sys_sum += $2; real_sum += $3; count++} \
END {printf "user_sum: " user_sum/count "\nsys_sum: " sys_sum/count  "\nreal_sum: " real_sum/count "\n"}'

echo ""

Comments

  1. 1. At 12:48 a.m. on 12 aug 2009, J Y (the author) said:

    actions are surrounded by {}

    [pattern] [{ action }]

  2. 2. At 1:59 a.m. on 25 aug 2009, J Y (the author) said:

    string concatenation is performed by writing expressions next to one another

  3. 3. At 2 a.m. on 25 aug 2009, J Y (the author) said:

    AWK doesn't have "types" of variables. There is one type only, and it can be a string or number. The conversion rules are simple. A number can easily be converted into a string. When a string is converted into a number, AWK will do so.

  4. 4. At 7:42 a.m. on 25 aug 2009, J Y (the author) said:

    awk uses associative array(map), the for statement scans over the [keys]

    Record a 1 for each word that is used at least once

    associate the fields as keys to a number

     {
         for (i = 1; i <= NF; i++)
             used[$i] = 1
     }
    
     # Find number of distinct words more than 10 characters long
    

    scan over the keys

     END {
         for (x in used)
             if (length(x) > 10) {
                 ++num_long_words
                 print x
             }
         print num_long_words, "words longer than 10 characters"
     }
    

Sign in to comment