![使用 awk 命令比较两个文件并打印所有列,然后缺少显示为 NA](https://linux22.com/image/58822/%E4%BD%BF%E7%94%A8%20awk%20%E5%91%BD%E4%BB%A4%E6%AF%94%E8%BE%83%E4%B8%A4%E4%B8%AA%E6%96%87%E4%BB%B6%E5%B9%B6%E6%89%93%E5%8D%B0%E6%89%80%E6%9C%89%E5%88%97%EF%BC%8C%E7%84%B6%E5%90%8E%E7%BC%BA%E5%B0%91%E6%98%BE%E7%A4%BA%E4%B8%BA%20NA.png)
文件一:
123, 234
345, 789
678, 900
文件2
123, abc
345, dnc
所需的输出(文件 1 中的所有列和文件 2 中的缺失值均为 NA):
123,234,abc
345,789,dnc
678,900,NA
答案1
如果你使用的话会更容易加入:
$ join -t, -a 1 -a 2 -j 1 -e ' NA' -o auto file1 file2
123, 234, abc
345, 789, dnc
678, 900, NA
答案2
awk -F ", ?" -v OFS=, 'FNR == NR { a[$1]=$2;next; };
{ if ($1 in a) print $1,$2,a[$1]; else print $1,$2,"NA"; }' file2 file1
答案3
awk
awk 'BEGIN{OFS=""}NR==FNR{a[$1]=$2;};NR>FNR{if($1 in a){print $0,", ",a[$1];}else{print $0,", NA";}}' file2 file1 > tmp
输出将存储在 tmp 中,正如您要求从 file3 更新一样
awk 'BEGIN{OFS=""}NR==FNR{a[$1]=$2;};NR>FNR{if($1 in a){print $0,", ",a[$1];}else{print $0,", NA";}}' file3 tmp
输出:
123, 234, abc, 2014/10/20
345, 789, dnc, NA
678, 900, NA, 2013/02/30