如何在awk中编写一个脚本,该脚本将从输入文件中写入10个值?谢谢。
我尝试过:
BEGIN
$2 == 0 && $3 == 2 { print $7}
$2 == 0 && $3 == 4 { print $7}
$2 == 0 && $3 == 5 { print $7}
$2 == 2 && $3 == 2 { print $7}
$2 == 2 && $3 == 4 { print $7}
$2 == 2 && $3 == 5 { print $7}
$2 == 3 && $3 == 2 { print $7}
$2 == 3 && $3 == 4 { print $7}
$2 == 3 && $3 == 5 { print $7}
$1 == "achil" { print $3}
我应该将所有内容写成一行吗? 什么时候需要用代码编写BEGIN,什么时候不需要?
输入文件为:
achil 1 197524.72437205614 197524.72437205614 0.43066284286002637
o 0 1 0 1 1 5.732821000
o 0 2 0 1 1 54002.804084586
o 0 3 0 1 1 0.088300000
o 0 4 0 1 1 150.924210421
o 0 5 0 1 1 108.520740945
o 0 6 0 1 1 0.380000000
o 0 7 0 1 1 0.004220000
o 0 8 0 1 1 0.000000000
o 0 9 0 1 1 0.000000000
o 0 10 0 1 1 0.000000000
o 0 11 0 1 1 0.000000000
o 2 1 0 1 1 73413.000000000
o 2 2 0 1 1 36176.166543543
o 2 3 0 1 1 0.560000000
o 2 4 0 1 1 229.480202654
o 2 5 0 1 1 7.032947038
o 2 6 0 1 1 0.480000000
o 2 7 0 1 1 0.000000000
o 2 8 0 1 1 0.000000000
o 2 9 0 1 1 0.000000000
o 2 10 0 1 1 0.000000000
o 2 11 0 1 1 0.000000000
o 3 1 0 1 1 365.256360000
o 3 2 0 1 1 51550.294729034
o 3 3 0 1 1 0.016710220
o 3 4 0 1 1 299.430719769
o 3 5 0 1 1 0.001070537
o 3 6 0 1 1 0.000036626
o 3 7 0 1 1 0.000009111
o 3 8 0 1 1 0.000000000
o 3 9 0 1 1 0.000000000
o 3 10 0 1 1 0.000000000
o 3 11 0 1 1 0.000000000
我想要由以下10个数字组成的输出:
197524.72437205614
54002.804084586
150.924210421
108.520740945
36176.166543543
229.480202654
7.032947038
51550.294729034
299.430719769
0.001070537
答案 0 :(得分:3)
您拥有的脚本几乎是正确的,但是在将其用作脚本时不需要BEGIN
子句。因为您在BEGIN
子句中包含的所有操作均在处理 前被执行。例如,考虑一种情况,当您必须为输出打印标题时,只需将其打印为
BEGIN { print "my-title-string-in-double quotes" }
将其写成一行或多行纯粹是样式问题,您所看到的内容整洁且可读性强。因此,您现在所需要做的就是定义一个内容为{p>的awk
脚本
#!/usr/bin/awk -f
$2 == 0 && $3 == 2 { print $7}
$2 == 0 && $3 == 4 { print $7}
$2 == 0 && $3 == 5 { print $7}
$2 == 2 && $3 == 2 { print $7}
$2 == 2 && $3 == 4 { print $7}
$2 == 2 && $3 == 5 { print $7}
$2 == 3 && $3 == 2 { print $7}
$2 == 3 && $3 == 4 { print $7}
$2 == 3 && $3 == 5 { print $7}
$1 == "achil" { print $3}
为其添加执行权限,
chmod +x script.awk
并以
运行awk -f script.awk input-file
但是话虽如此,您的条件很容易使用模式匹配运算符编写为
$2 ~ /^(0|2|3)$/ && $3 ~ /^(2|4|5)$/ { print $7; next } $1 == "achil" { print $3 }