我有 30 个文件,名为 UE1.dat、UE2.dat ....,每个文件有 4 列。下面给出了 UE1.dat 和 UE2.dat 的列结构示例。
UE1.dat
1 4 2 1
2 2 3 3
3 2 4 4
4 4 4 2
UE2.dat
2 6 8 7
4 4 9 6
7 1 1 2
9 3 3 3
所以,我尝试使用以下代码:
for((i=1;i<=30;i++)); do awk 'NR$i {printf $1",";next} 1; END {print ""}' UE$i.dat; done > UE_all.dat
仅从每个文件中获取第一列并将它们写入一个文件中,并且各列并排,下面给出了所需的输出。
1 2
2 4
3 7
4 9
但不幸的是,代码将它们按行排序,你能给出提示吗?
提前谢谢您!
最佳答案
在 awk 中你可以这样做:
1) 将此代码放入名为 output_data_from_multiple_files.awk
的文件中:
BEGIN {
# All the input files are processed in one run.
# filenumber counts the number of input files.
filenumber = 1
}
{
# FNR is the input record number in the current input file.
# Concatenate the value of the first column in the corresponding
# line in the output.
output[FNR] = output[FNR] " " $1
# FNR == 1 means we are processing a new file.
if (FNR == 1) {
++filenumber
}
}
END {
# print the output
for (i=1; i<=FNR; i++)
printf("%s\n", output[i])
}
2) 运行 awk -f output_data_from_multiple_files.awk UE*
所有文件都在 awk
的单次执行中处理。 FNR
是当前输入文件中的输入记录号。 filenumber
用于统计已处理文件的数量。输入文件中读取的值连接在output
数组中。
关于awk - 如何通过awk从一个文件中并排列的多个文件中输出数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31881537/