如何将一个文件逐行放入另一个文件

How to put a file into another one line by line

我有两个行号完全相同的文件。它们如下所示:

File-A
X1 Y1 Z1 T1
X2 Y2 Z2 T2

File-B
M1 N1
M2 N2

所以,我想合并它们,以便最终文件 (File-C) 如下所示:

X1 Y1 M1 Z1 T1
X2 Y2 M2 Z2 T2

很简单,我需要将 File-B 中每一行的第一个字段作为第三个字段放入最终文件中。我如何使用 bash 命令做到这一点?

编辑

在提供答案后,我尝试合并这些文件,但根据该列上的值更改来自文件 B 的列。所以,按照我想要的 file-C 如下:

  X1 Y1 "foo" Z1 T1    #if M1 == 3
    X2 Y2 "boo" Z2 T2  # if M2 == 4 
    X3 Y3 "goo" Z3 T3  # if M2 == 2
    X4 Y4 "too" Z4 T4  # if M2 == 1

保证 M2 将是这些值之一。

能否请您尝试关注 awk,如果这对您有帮助,请告诉我。

awk 'FNR==NR{a[FNR]= FS ;b[FNR]= FS ;next} {print a[FNR],,b[FNR]}' File-A File-B

输出如下。

X1 Y1 M1 Z1 T1
X2 Y2 M2 Z2 T2

如果您想将此输出放入名为 C 的 Input_file 中,只需在上述命令的末尾添加 > "File-C"

现在也添加了非线性形式的解决方案,并附有代码说明。

awk '
FNR==NR{                ##FNR==NR condition will be TRUE when first Input_file named File-A is being read. If this condition is TRUE do following.
  a[FNR]= FS ;      ##Creating an array named a whose index is current line and value is 1st and 2nd columns with a space in between them.
  b[FNR]= FS ;      ##Creating an array named b whose index is current line number and value is 3rd and 4th column with a space in them.
  next                  ##using next will make sure NO further statements are being used.
}
{
  print a[FNR],,b[FNR]##This print statement will be executed when 2nd Input_file named File-B is being read because during first Input_file read it will NEVER come on this statement, so simply printing here array a value with index of current line number then printing 1st column and then printing array b whose index is current line.
}
' File-A File-B         ##Mentioning Input_files here.

EDIT1: 由于 OP 在实际问题本身中添加了一个小要求,因此在这里也添加了编辑后的解决方案。

awk 'FNR==NR{a[FNR]= FS ;b[FNR]= FS ;next} ==3{val="foo"} ==4{val="boo"}==2{val="goo"} ==1{val="too"}{print a[FNR],val,b[FNR]}' File-A File-B

第一个问题的答案:

paste file_a file_b | awk '{print , , , , ;}'

file_a

X1 Y1 Z1 T1
X2 Y2 Z2 T2

file_b

M1 N1
M2 N2

输出

X1 Y1 M1 Z1 T1
X2 Y2 M2 Z2 T2