这是这两个问题的演变, 在这里和这里 。
对于我自己的学习,我试图用下面的代码完成两件(更多)事情:
而不是用 # myscript -F "," file_to_process 调用我的脚本,我 怎样才能将' -F "," ''部分折叠到脚本本身中?我怎样才能初始化一个变量,以便我只赋值一次(忽略后续匹配?从脚本中可以看出,我在每个规则中解析秒和微秒,我想保留sec的第一个赋值我可以从printf()语句中的后续匹配中减去它。
#!/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) }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:
Instead of invoking my script with # myscript -F "," file_to_process, how can I fold in the '-F ","' part into the script itself?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) }最满意答案
使用BEGIN子句:
BEGIN { FS = "," var1 = "text" var2 = 3 etc. }这是在行处理语句之前运行的。 FS是场分隔符。
如果你想分析一个值并保留它,这取决于你是只想要第一个还是你想要每个之前的值。
要保持第一个:
FNR==1 { keep=$1 }保持前一个:
BEGIN { prevone = "initial value" } /regex/ { do stuff with $1 do stuff with prevone prevone = $1 }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 }更多推荐
发布评论