我目前正在尝试比较 bash 中的两个平面文件。第一个文件将包含由 | 分隔的三列 第二个将有两列由|分隔。我想获取第二个文件中缺少的输入并将其放入第一个文件中。我只关心将文件 2 中缺少的两个列接管到文件 1。
示例文件
文件一:
a|蓝色|3
b|黄色|1
c|绿色|2
文件二:
a|蓝色
b|黄色
c|绿色
d|紫色
输出文件:
a|蓝色|3
b|黄色|1
c|绿色|2
d|紫色
这应该有效:
# Set the input field separator to "|"
awk -F'|' '
# Load the second file into an array called "a". NR==FNR allows us to perform this action
# until first file is complete
NR==FNR { a[$0]; next }
# We check the existence of first and second column of first file in array. If it is present
# we delete that array element. 1 at the end allows us to print the line from first file as is.
($1 FS $2 in a) { delete a[$1 FS $2] }1
# This action takes place at the very end. Whatever is left in our array we iterate through
# and print it. This can cause the output to appear in any order hence sort is needed.
END { for (l in a) print l }' f2 f1
输出:
$ head f*
==> f1 <==
a|blue|3
c|green|2
b|yellow|1
==> f2 <==
a|blue
c|green
b|yellow
d|purple
$ awk -F'|' '
NR==FNR { a[$0]; next }
($1 FS $2 in a) { delete a[$1 FS $2] }1
END { for (l in a) print l }' f2 f1
a|blue|3
c|green|2
b|yellow|1
d|purple