如何在Bash中逐行合并两个文件

sem*_*teu 164 unix bash

我有两个文本文件,每个文件都包含一行信息

file1.txt            file2.txt
----------           ---------
linef11              linef21
linef12              linef22
linef13              linef23
 .                    .
 .                    .
 .                    .
Run Code Online (Sandbox Code Playgroud)

我想使用bash脚本逐行合并这些文件,以获得:

fileresult.txt
--------------
linef11     linef21
linef12     linef22
linef13     linef23
 .           .
 .           .
 .           .
Run Code Online (Sandbox Code Playgroud)

怎么能在Bash中完成?

Mar*_*ers 251

你可以使用paste:

paste file1.txt file2.txt > fileresults.txt
Run Code Online (Sandbox Code Playgroud)

  • @SOaddict``` paste -d"\n"*> results.txt``` (7认同)
  • `paste -d“”`连接没有分界线,空格的行 (4认同)
  • 如果我想使用分隔符,它如何工作? (2认同)

gho*_*g74 19

这是非粘贴方法

AWK

awk 'BEGIN {OFS=" "}{
  getline line < "file2"
  print $0,line
} ' file1
Run Code Online (Sandbox Code Playgroud)

巴什

exec 6<"file2"
while read -r line
do
    read -r f2line <&6
    echo "${line}${f2line}"
done <"file1"
exec 6<&-
Run Code Online (Sandbox Code Playgroud)


vth*_*tha 10

试试以下.

pr -tmJ a.txt b.txt > c.txt
Run Code Online (Sandbox Code Playgroud)

  • 另外,如果要更改分隔符,请使用 -s 选项。(+1) (3认同)

Chr*_*zig 8

校验

man paste
Run Code Online (Sandbox Code Playgroud)

可能跟着像untabifyor 这样的命令tabs2spaces

  • 使用-d选项指定tab以外的分隔符 (7认同)

小智 6

You can use paste with the delimiter option if you want to merge and separate two texts in the file

paste -d "," source_file1 source_file2 > destination_file
Run Code Online (Sandbox Code Playgroud)

Without specifying the delimiter will merge two text files using a Tab delimiter

paste source_file1 source_file2 > destination_file
Run Code Online (Sandbox Code Playgroud)