tags:

views:

49

answers:

1

This is the evolution of these two questions, here, and here.

For mine own learning, I'm trying to accomplish two (more) things with the code below:

  1. Instead of invoking my script with # myscript -F "," file_to_process, how can I fold in the '-F ","' part into the script itself?
  2. How can I initialize a variable, so that I only assign a value once (ignoring subsequent matches? You can see from the script that I parse seconds and micro seconds in each rule, I'd like to keep the first assignment of sec around so I could subtract it from subsequent matches in the printf() statement.

    #!/usr/bin/awk -f
    /DIAG:/  {
        lbl = $3;
        sec = $5;
        usec = $6;
        /Test-S/ {
            stgt = $7;
            s1  = $30;
            s2  = $31;
        }
        /Test-A/ {
            atgt = $7;
            a = $8;
        }
        /Test-H/ {
            htgt = $7;
            h = $8;
        }
        /Test-C/ {
            ctgt = $7;
            c = $8;
        }
    }
    /WARN:/ {
        sec = $4;
        usec = $5;
        m1 = $2;
        m2 = $3
    }
    {
     printf("%16s,%17d.%06d,%7.2f,%7.2f,%7.2f,%7.2f,%7.2f,%7.2f,%7.2f,%7.2f,%7.2f,%5d,%5d\n", lbl, sec, usec, stgt, s1, s2, atgt, a, htgt, h, ctgt, c, m1, m2)
    }
    
+4  A: 

Use a BEGIN clause:

BEGIN { FS = ","
    var1 = "text"
    var2 = 3
    etc.
}

This is run before the line-processing statements. FS is the field separator.

If you want to parse a value and keep it, it depends on whether you want only the first one or you want each previous one.

To keep the first one:

FNR==1 {
    keep=$1
}

To keep the previous one:

BEGIN {
    prevone = "initial value"
}

/regex/ {
    do stuff with $1
    do stuff with prevone
    prevone = $1
}
Dennis Williamson
I wish I could hand out extra points for brevity and being on point. Nicely done.
Jamie