从 2 个文件中取出第一列并将其写入第三个文件

Rah*_*til 5 text-processing

假设我有 2 个文件,ABC.txt&PQR.txt以下面显示的数据为例:

ABC.txt:

ABC DEF
Run Code Online (Sandbox Code Playgroud)

PQR.txt:

PQR XYZ
Run Code Online (Sandbox Code Playgroud)

我想grep从两个文件中列 1 并写入第三个文本文件。怎么做到呢?

我的预期输出是 (output.txt):

ABC PQR
Run Code Online (Sandbox Code Playgroud)

ter*_*don 7

这里有几种方法:

  • 使用pastecut

    $ paste -d ' ' <(cut -d' ' -f 1 ABC.txt ) <(cut -d' ' -f 1 PQR.txt ) > output.txt
    ABC PQR
    
    Run Code Online (Sandbox Code Playgroud)

    如果您的系统不支持进程替换,请改用:

    $ cut -d' ' -f 1 ABC.txt > /tmp/aa; cut -d' ' -f 1 PQR.txt > /tmp/bb; paste -d ' ' /tmp/aa /tmp/bb
    
    Run Code Online (Sandbox Code Playgroud)
  • 使用awk(感谢@Costas):

    awk 'FNR==NR{a[FNR]=$1; next}{print a[FNR],$1}' ABC.txt PQR.txt > output.txt
    
    Run Code Online (Sandbox Code Playgroud)

    特殊变量FNR是当前输入文件NR的行号,通常是输入的行号,无论它来自哪个文件。两者仅在读取第一个输入文件时相等。因此,第一个文件的第一个字段保存在a数组 ( a[FNR]=$1) 中,其键是行号,其值是第一个字段。然后,当到达第二个文件时,我们打印对应于其行号 ( a[NR]) 和当前行的第一个字段的值。


Cos*_*tas 5

您可以计算行nl并使用join

join -o 1.2,2.2 <(nl ABC.txt) <(nl PQR.txt) > OUT.file
Run Code Online (Sandbox Code Playgroud)

或者通过 cat -n

join -o 1.2,2.2 <(cat -n ABC.txt) <(cat -n PQR.txt) > OUT.file
Run Code Online (Sandbox Code Playgroud)

就像解析 for/while 循环中输入的两个文件一样您可以只使用bash builtins

while read -u 3 a b && read -u 4 c d
do
  echo "$a $c"
done 3< ABC.txt 4< PQR.txt >OUT.txt
Run Code Online (Sandbox Code Playgroud)


gle*_*man 4

假设输入文件中的字段由一个空格分隔,我会写:

paste -d " " ABC.txt PQR.txt | cut -d " " -f 1,3 > Output.txt
Run Code Online (Sandbox Code Playgroud)

处理任意空格,以及每个文件超过 2 列,并假设您的 shell 是 bash/ksh/zsh(?)

paste -d " " <(awk '{print $1}' ABC.txt) <(awk '{print $1}' PQR.txt) > Output.txt
Run Code Online (Sandbox Code Playgroud)