IT源码网

linux之shell合并两个文件

jackei 2024年02月27日 程序员 43 0

我有两个文件,我想通过匹配 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. 


评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!