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