[英]How to append each column of file1 to a specific field of file2 and make a new output file?
I want to append each column of file 1 as the 4th column of file 2 and export as a new file with the column number from file 1 or something similar as the output name. 我想将文件1的每一列作为文件2的第4列附加并导出为新文件,其中包含来自文件1的列号或类似于输出名称的列号。
Input File 1 and 2 have the same number of rows: 输入文件1和2具有相同的行数:
Input File 1 has N columns: 输入文件1有N列:
12 23 34 .....
33 34 23
67 09 34
45 67 34
65 76 44
64 33 96
Input File 2 originally has 5 columns 输入文件2最初有5列
AA BB FF DD 6
AA CC HH NN 7
AA DD II RR 4
AA EE JJ PP 2
AA FF KK QQ 9
AA GG LL SS 8
For example, the first 3 output files would look like this: 例如,前3个输出文件如下所示:
Output File 1 (column 1): 输出文件1(第1列):
AA BB FF 12 DD 6
AA CC HH 33 NN 7
AA DD II 67 RR 4
AA EE JJ 45 PP 2
AA FF KK 65 QQ 9
AA GG LL 64 SS 8
Output File 2 (column 2): 输出文件2(第2列):
AA BB FF 23 DD 6
AA CC HH 34 NN 7
AA DD II 09 RR 4
AA EE JJ 67 PP 2
AA FF KK 76 QQ 9
AA GG LL 33 SS 8
Output File 3 (column 3): 输出文件3(第3列):
AA BB FF 34 DD 6
AA CC HH 23 NN 7
AA DD II 34 RR 4
AA EE JJ 34 PP 2
AA FF KK 44 QQ 9
AA GG LL 96 SS 8
The new file names can be file1, file2, file3...or column1, column2, column3....or something similar. 新文件名可以是file1,file2,file3 ...或column1,column2,column3 ....或类似的东西。 How can I achieve this please?
我怎么能实现这个目标呢? (for loop, awk, paste, etc.)
(用于循环,awk,粘贴等)
Any suggestions would be appreciated. 任何建议,将不胜感激。
If your columns are tab-separated, you can easily profit from cut
and paste
: 如果您的列以制表符分隔,则可以轻松地从
cut
和paste
获益:
for i in {1..N} ; do # Insert the real N here, or change to $(seq 1 $N)
cut -f1-3 input2 | \
paste - \
<(cut -f$i input1) \
<(cut -f4- input2) \
> output$i
done
This method processes each file only once, which is a help if the files are large. 此方法仅处理每个文件一次,如果文件很大,这是一个帮助。 It does, however, require the first file to be stored in memory:
但是,它确实需要将第一个文件存储在内存中:
awk '
NR==1 {n=NF}
NR==FNR {
for (i=1; i<=n; i++)
file1[i, FNR]=$i
next
}
{
for (i=1; i<=n; i++) {
filename = "merged" i
print $1, $2, $3, file1[i, FNR], $4, $5 >> filename
}
}
' file1 file2
Something like this is all you need: 这就是你需要的东西:
awk '
NR==FNR { hd=$1" "$2" "$3"; tl=$4" "$5; next }
{ for (i=1;i<=NF;i++) {
print hd, $i, tl > "file" i
}
}
' file2 file1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.