shell - 如何使用 awk 获取 file1 中而不是 file2 中存在的已创建数组的值?
问题描述
假设 file1 有内容:
1=apple
2=mango
3=banana
4=litchi
7=papaya
和文件2:
1=apple
2=banana
3=grapes
4=kiwi
5=orange
6=peach
我需要最终输出为:
1=apple
2=mango
3=banana
4=litchi
7=papaya
5=orange
6=peach
为文件 1 创建一个关联数组并比较文件 2 中的数组元素,但是如何获取文件 1 中和文件 2 中不存在的行的数组。
使用此代码:
awk -F"=" 'FNR==NR{a[$1]=$0;next;}
{
if ($1 in a && $1)
print a[$1]
else if(!$1)
print
else
print $1"="$NF
}' file1 file2
Output
--------
1=apple
2=mango
3=banana
4=litchi
5=orange
6=peach
我能拿到钥匙 6,没有运气拿到钥匙 7。
如果我添加这个条件:
...
else if(!($1 in a)){ for (i in a) {
print a[i]}}
...
我得到的输出为:
1=apple
2=mango
3=banana
4=litchi
3=banana
2=mango
1=apple
4=litchi
7=papaya
3=banana
2=mango
1=apple
4=litchi
7=papaya
请帮我找出正确的条件。
解决方案
另一个awk:
$ awk '
BEGIN {
FS=OFS="=" # field separator
}
NR==FNR { # process file1
a[$1]=$0 # index on first field
b[$1] # this is used for seen ones
next
}
{ # process file2
if($1 in a) { # if first field found in file1
print a[$1] # print that instead
delete b[$1] # delete from b to mark it as seen
} else
print $0 # print file2 entry if was not in file1
}
END { # in the end
for(i in b) # the ones from file1 not in file2
print a[i] # output
}' file1 file2
输出:
1=apple
2=mango
3=banana
4=litchi
5=orange
6=peach
7=papaya
推荐阅读
- node.js - 如何修复 ReferenceError:nodeJs 中未定义错误
- c# - Automapper:尝试使用私有设置器映射到属性
- java - 错误 - 尝试在空对象引用上调用虚拟方法___________setOnClickListener(android.view.View$OnClickListener)'
- dialogflow-es - 创建谷歌助手支持的Dialogflow代理
- sql - 复杂结果和 NULLS 的位置 - SQL C#
- java - 如何在不使用 PO 关闭 webdriver 的情况下运行测试?
- javascript - if 语句有替代方法吗?
- node.js - 谷歌身份验证后如何发回数据以做出反应
- python - 以内存有效的方式使用 tf.data.Dataset 加载数据的最佳方法是什么
- routes - ns3 向节点添加处理(路由)延迟