如何在awk中保存变量?

Ele*_*reg 2 awk

How can I print the filename and the result of 1/2*(a+b), where a is the 1st field of the 2nd line and b is the 1st field of the last line please? I do not know how to save the values into variables as constants. Many thanks

awk -v a=$(NR==2{print $1}) b=$(END(print $1)) '{print FILENAME, 1/2*(a+b)}' rv*.out 
Run Code Online (Sandbox Code Playgroud)

file1

4 5 6
14545.5886 2 6
2 3 5
45457.5462 8 6
Run Code Online (Sandbox Code Playgroud)

file2

1 2 
34441.4545 8
6 8
8 8 
54447.4545 1
Run Code Online (Sandbox Code Playgroud)

Output for:

for file in test1.txt test2.txt; do 
    awk ' (NR==2){a=$1} END{print FILENAME, 1/2*(a+$1)}' "$file" >> stredni.txt; 
done

test1.txt 7272.79
test2.txt 17220.7
Run Code Online (Sandbox Code Playgroud)

Desired result:

test1 30001.5674
test2 44444.4545
Run Code Online (Sandbox Code Playgroud)

ter*_*don 6

语法var=$(something)是 shell 语法(而不是awk),这意味着“运行命令something并将结果存储在 shell 变量中$var”。您似乎希望它以某种方式链接到您的awk脚本,因为NR==2etc 是 awk 语句。那行不通。

此命令将打印您期望的输出:

$ for file in file1 file2; do 
    awk ' (NR==2){a=$1} END{print FILENAME, 1/2*(a+$1)}' "$file"; 
  done
file1 30001.6
file2 44444.5
Run Code Online (Sandbox Code Playgroud)

您也可以使用 GNU awk( gawk)来做到这一点:

$ gawk 'FNR==2{a=$1}ENDFILE{print FILENAME, 1/2*(a+$1)}' file1 file2
file1 30001.6
file2 44444.5
Run Code Online (Sandbox Code Playgroud)

  • END 部分中的“$1”(或“$0”或任何其他字段)的值未由 POSIX 定义。在某些 awks(例如 gawk)中,它将是读取最后一条记录时的值,在其他 awks(显然是 OP 使用的任何一个)中,它将为空,而在其他人中,它仍然可以是其他任何东西。为了可移植到所有 awk,您需要 `awk 'NR==2{a=$1} {b=$1} END{print FILENAME, 1/2*(a+b)}' "$file"` (3认同)