awk脚本,不正确的应答QUOT;若"声明 [英] Awk script, incorrect response of "if" statement
问题描述
我要寻求帮助一个方面存在如下问题:
I want to ask for help regarding a following problem:
我有两个文件,文件1:
I have two files, file 1:
1 apples
2 bananas
3 orange
4 prunes
和文件2:
1 oranges
2 apples
3 nuts
我需要从文件2提取所有不符合文件1线(即3坚果)。我写了 AWK
脚本:
#!/bin/awk -f
BEGIN {
while (getline <hdr>0) {
a[i++]=$2;
}
close (hdr);
}
{ for (i in a) {
if (a[i]!=$2) {
print a[i];
}
}
}
我的命令行:
awk -v hdr=file2 -f script_name file1
但是,我得到的结果是文件2几次的只是内容。
这个问题可能会是什么?
But the result that I got is just the content of the file2 several times. What the problem might it be?
推荐答案
有很多事情不对您的code(即使输入文件)。假设行号是你输入的一部分,你可以试试这个
there are many things wrong with your code (even with the input files). Assuming the line numbers are part of your input you can try this
$ join -v2 -12 -22 -o2.1,2.2 <(sort -k2 file1) <(sort -k2 file2)
这将返回
3 nuts
1 oranges
如果您在您的第一个文件变橙到橘子,你将只能得到坚果。
if you change "orange" to "oranges" in your first file you will only get the nuts.
有一个类似的功能 AWK
脚本会
A similar functionality awk
script will be
$ awk 'NR==FNR{a[$2]=$0; next}
$2 in a{delete a[$2]}
END{for(k in a) print a[k]}' file2 file1
3 nuts
1 oranges
请注意文件2首先提供。
note file2 is provided first.
这将是更简单然而,其他方式
It will be simpler however, the other way around
$ awk 'NR==FNR{a[$2]; next} !($2 in a)' file1 file2
1 oranges
3 nuts
注意,文件1,首先提供的。
note that file1 is provided first.
这篇关于awk脚本,不正确的应答QUOT;若&QUOT;声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!