首页 > 解决方案 > 如何使用 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

请帮我找出正确的条件。

标签: shellawk

解决方案


另一个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

推荐阅读