linux - shell合并两个文件

标签 linux shell join awk

我有两个文件,我想通过匹配 file1 和 file2 中的第二个和第一个字段来连接 file1 和 file2,并将第一个数据从 file1 写入 file2

文件1:

5439725407 uQkiJRPOZLLJkc
5368657511 eWGDnOcNgxjBK
5322202068 dNsUkWOMk9lNJ

文件2:

uQkiJRPOZLLJkc,00087b8dbe6fdc3a5725a0a77fa4e37f3db10440d8b0da2d3935cb0f8f4f9089,1
eWGDnOcNgxjBK,0008958b743f8b786fa7f080348f3180f8e410890a07995878c1fcbda66706b4,1
dNsUkWOMk9lNJ,0008bc14ecce6150bef44f657e12314b8b2c37a5730bf88fc81b66d5f77ed8be,1

输出文件:

uQkiJRPOZLLJkc,00087b8dbe6fdc3a5725a0a77fa4e37f3db10440d8b0da2d3935cb0f8f4f9089,1,5439725407
eWGDnOcNgxjBK,0008958b743f8b786fa7f080348f3180f8e410890a07995878c1fcbda66706b4,1,5368657511
dNsUkWOMk9lNJ,0008bc14ecce6150bef44f657e12314b8b2c37a5730bf88fc81b66d5f77ed8be,1,5322202068

最佳答案

以下 awk 解决方案也可能对您有所帮助。

awk 'FNR==NR{a[$1]=$0;next} ($2 in a){print a[$2] "," $1}' FS="," filE2  FS=" " filE1

输出如下。

uQkiJRPOZLLJkc,00087b8dbe6fdc3a5725a0a77fa4e37f3db10440d8b0da2d3935cb0f8f4f9089,1,5439725407
eWGDnOcNgxjBK,0008958b743f8b786fa7f080348f3180f8e410890a07995878c1fcbda66706b4,1,5368657511
dNsUkWOMk9lNJ,0008bc14ecce6150bef44f657e12314b8b2c37a5730bf88fc81b66d5f77ed8be,1,5322202068

编辑:现在也在这里添加非单行解决方案形式的解释。

awk '
FNR==NR{                      ##Checking condition here FNR==NR, which will be TRUE when first Input_file will be read.
  a[$1]=$0;                   ##Creating an array named a whose index is first field of current line and value is current line.
  next                        ##next statement will skip all further statements.
}                             ##Following block will be executed when 2nd Input_file is being read.
($2 in a){                    ##checking if 2nd field of current line is present in array a, if yes then do following.
  print a[$2] "," $1          ##Printing the value of array a whose index is $2 of current line, printing comma and then printing first field of current line.
}
' FS="," filE2  FS=" " filE1  ##Setting field separator as comma for Input_file2 and setting field separator as space for Input_file1 here.

关于linux - shell合并两个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47057926/

相关文章:

mysql - 查询两个表,其中一行与另一行相似

linux - mongodb远程连接问题

java - 使用 java Runtime.exec() 执行 yum 安装程序并捕获其下载进度

linux - 远程执行需要输入的 bash 脚本

linux - 使用 Go 运行带参数的 sh/bash/python 脚本

linux - 使用 FFMPEG 转换为 mp4 的 Shell 脚本会产生两次附加 .mp4 扩展名的新视频

linux - -bash : pscp: command not found

linux - 从 Bash 脚本执行 GREP/CUT 命令时出现问题

R:在填充数据框 B 中的一行之前,使用某个日期的数据框 A 中的值

mysql - group by 无法正确连接两个表