开发者

How can I embed arguments in an awk script?

开发者 https://www.devze.com 2022-12-08 07:11 出处:网络
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:

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


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消