我怎样才能在awk脚本中嵌入参数?(How can I embed arguments in an awk script?)

编程入门 行业动态 更新时间:2024-10-28 19:21:26
我怎样才能在awk脚本中嵌入参数?(How can I embed arguments in an awk script?)

这是这两个问题的演变, 在这里和这里 。

对于我自己的学习,我试图用下面的代码完成两件(更多)事情:

而不是用 # 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 }

更多推荐

本文发布于:2023-08-04 16:57:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1417757.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:脚本   参数   awk   script   arguments

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!