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

时间:2017-09-29 16:01:48

标签: bash file text-processing

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

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的列。所以,通过以下我想要文件-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将成为这些值中的一个。

2 个答案:

答案 0 :(得分:2)

请你试试关注awk并告诉我这是否对你有帮助。

.ui-menu li.ui-menu-item{
    display:inherit;
}

输出如下。

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

如果要将此输出转换为名为C的Input_file,只需在上面的命令末尾添加X1 Y1 M1 Z1 T1 X2 Y2 M2 Z2 T2

现在添加非单线形式的解决方案,并解释代码。

> "File-C"

EDIT1:由于OP在实际问题中添加了一个小要求,因此在此处添加了已编辑的解决方案。

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]=$1 FS $2;      ##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]=$3 FS $4;      ##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],$1,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.

答案 1 :(得分:0)

回答第一个问题:

paste file_a file_b | awk '{print $1, $2, $5, $3, $4;}'

<强> 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