![为什么 awk 脚本会打乱最后两个字段?](https://linux22.com/image/156786/%E4%B8%BA%E4%BB%80%E4%B9%88%20awk%20%E8%84%9A%E6%9C%AC%E4%BC%9A%E6%89%93%E4%B9%B1%E6%9C%80%E5%90%8E%E4%B8%A4%E4%B8%AA%E5%AD%97%E6%AE%B5%EF%BC%9F.png)
我的工作文件看起来像这样
Time[s] A_in B_in C_in D_in E_in
0.000000E+00 1.120200E-02 1.432000E-01 2.331500E-04 2.349800E-03 2.800000E-03
2.500000E-01 1.751279E-04 1.553696E-01 3.172887E-09 7.512772E-09 5.009619E-09
5.000000E-01 1.741500E-04 1.553710E-01 3.102978E-09 7.609057E-09 4.952014E-09
7.500000E-01 1.733357E-04 1.553721E-01 3.037365E-09 7.730931E-09 4.893341E-09
我想要的输出是
Column_header = ID Time[s] A_in Time[s] B_in Time[s] C_in Time[s] D_in Time[s] E_in
我目前的代码输出是
Column_header = ID Time[s] A_in Time[s] B_in Time[s] C_in Time[s] E_in Time[s] D_in
这是我的片段
Column_headers=$(awk ' BEGIN{OFS=" ";}
FNR==1 { for (n=1;n<=NF;n++) { if ($n ~ /_in$/) cols[$n]=n; }}
NR==1 {
# print header
printf "ID" " "
}
END {
for (c in cols) {printf " " "Time[s]" " " c}
}
' file.txt
正如你所看到的,问题是我的代码正在打乱最后两列,我根本不知道。
答案1
只需简单地执行以下操作,不需要数组或复杂的代码:
$ awk '{ OFS=" Time[s] "; $1="ID"; print; exit }' infile
将结果分配给 shell 变量:
$ column_headers=$(awk '{ OFS=" Time[s] "; $1="ID"; print; exit }' infile)
$ echo "$column_headers"
ID Time[s] A_in Time[s] B_in Time[s] C_in Time[s] D_in Time[s] E_in
或者,如果您不知道第一个字段标题名称,请执行以下操作:
$ awk '{ OFS=" "$1" "; $1="ID"; print; exit }' infile
ID Time[s] A_in Time[s] B_in Time[s] C_in Time[s] D_in Time[s] E_in