我想合并两个文件,列和行,但在使用bash时有困难。以下是我想做的事。
File1:
1 2 3
4 5 6
7 8 9File2:
2 3 4
5 6 7
8 9 1预期输出文件:
1/2 2/3 3/4
4/5 5/6 6/7
7/8 8/9 9/1这只是一个例子。实际文件是两个1000x1000数据矩阵。
对怎么做有什么想法吗?谢谢!
发布于 2020-12-03 22:52:41
或者使用paste + awk
paste file1 file2 | awk '{ n=NF/2; for(i=1; i<=n; i++) printf "%s/%s ", $i, $(i+n); printf "\n"; }'请注意,此脚本在最后一个值之后添加了一个尾随空间。这可以避免使用更复杂的awk脚本,或通过管道输出通过一个额外的命令,例如。
paste file1 file2 | awk '{ n=NF/2; for(i=1; i<=n; i++) printf "%s/%s ", $i, $(i+n); printf "\n"; }' | sed 's/ $//'awk解决方案,没有额外的sed。多亏了Jonathan Leffler。(我知道这是有可能的,但我懒得去想这件事。)
awk '{ n=NF/2; pad=""; for(i=1; i<=n; i++) { printf "%s%s/%s", pad, $i, $(i+n); pad=" "; } printf "\n"; }'发布于 2020-12-03 22:19:23
paste + perl版本,可以处理任意数量的列,而不必在内存中保存整个文件:
paste file1.txt file2.txt | perl -MList::MoreUtils=pairwise -lane '
my @a = @F[0 .. (@F/2 - 1)]; # The values from file1
my @b = @F[(@F/2) .. $#F]; # The values from file2
print join(" ", pairwise { "$a/$b" } @a, @b); # Merge them together again'它使用非标准但有用的List::MoreUtils模块;通过操作系统包管理器或喜爱的CPAN客户端安装。
发布于 2020-12-03 22:28:02
假设:
F29的行数和/或字段
一种awk解决方案:
awk '
# first file (FNR==NR):
FNR==NR { for ( i=1 ; i<=NF ; i++) # loop through fields
{ line[FNR,i]=$(i) } # store field in array; array index = row number (FNR) + field number (i)
next # skip to next line in file
}
# second file:
{ pfx="" # init printf prefix as empty string
for ( i=1 ; i<=NF ; i++) # loop through fields
{ printf "%s%s/%s", # print our results:
pfx, line[FNR,i], $(i) # prefix, corresponding field from file #1, "/", current field
pfx=" " # prefix for rest of fields in this line is a space
}
printf "\n" # append linefeed on end of current line
}
' file1 file2注意到
移除注释到declutter代码内存使用量将随着矩阵大小的增加而增加(对于小型字段和关于1000 x 1000矩阵的操作注释可能不是问题)以上所述产生:
1/2 2/3 3/4
4/5 5/6 6/7
7/8 8/9 9/1https://stackoverflow.com/questions/65134601
复制相似问题