我想计算最多15个文件: - ifile1.txt,ifile2.txt,.....,ifile15.txt。每个文件的列数和行数相同。但其中一些缺少价值观。部分数据显示为
ifile1.txt ifile2.txt ifile3.txt
3 ? ? ? . 1 2 1 3 . 4 ? ? ? .
1 ? ? ? . 1 ? ? ? . 5 ? ? ? .
4 6 5 2 . 2 5 5 1 . 3 4 3 1 .
5 5 7 1 . 0 0 1 1 . 4 3 4 0 .
. . . . . . . . . . . . . . .
我想在不考虑缺失值的情况下编写这15个文件的最大值。
ofile.txt
4 2 1 3 . (i.e. max of 3 1 4, max of ? 2 ? and so on)
5 ? ? ? .
4 6 5 2 .
5 5 7 4 .
. . . . .
我正在尝试这个,但没有得到结果。
awk '
{
for( i = 1; i <= FNR; i++){
for( j = 1; j <= NF; j++) printf "%s ", {
max=="" || $i > max {max=$i} END{ print max}' FS="|" : "?"
print ""
}
}
' ifile*
答案 0 :(得分:2)
您可以尝试此awk
计划:
awk '{
for(i=1;i<=NF;i++)
if($i>a[FNR,i] && $i!="?")
a[FNR,i]=$i
}
END{
for(j=1;j<=FNR;j++)
for(i=1;i<=NF;i++)
printf "%s%s",(a[j,i]?a[j,i]:"?"),(i<NF?OFS:ORS)
}' file1 file2 file3
4 2 1 3
5 ? ? ?
4 6 5 2
5 5 7 1
默认循环将从所有文件中获取值,并将最高值存储到数组a
中。
END
语句循环遍历数组以显示值。
这取决于FNR
,正在处理的当前文件的行号以及NF
当前行的字段数。
答案 1 :(得分:1)
占用一些内存,但每个文件只有一个循环
awk '{L=FNR==1?"":L ORS;for (i=1;i<=NF;i++){R=FNR":"i; M[R]=M[R]*1<=$i*1?$i:M[R];L=L OFS M[R]}}END{print L}' ifile*
解释
awk '{
#Lines output buffer is reset on first line of file and append with new line otherwise
L=FNR==1?"":L ORS
# for every field (number in line)
for (i=1;i<=NF;i++){
# create a index reference (line + field)
R=FNR":"i
# set in an array the max value between old value for this reference and current one. the ( * 1 ) allow to compare ? and number but only used in compare values, not assignation to keep the "?"
M[R]=M[R]*1<=$i*1?$i:M[R]
# Append the value to Output lines
L=L OFS M[R]}}
# after last line of last file, print the Output lines
END{print L}
' ifile*