【问题标题】:AWK print out the mis-matched records from files comparisonAWK 从文件比较中打印出不匹配的记录
【发布时间】:2021-12-31 07:03:13
【问题描述】:

我需要您的帮助才能从 AIX 6.x 上的以下示例中找到 Employee.txt 中不匹配的列表。

员工.txt

1|Sam|Smith|Seatle
2|Barry|Jones|Seatle
3|Garry|Brown|Houston
4|George|Bla|LA
5|Celine|Wood|Atlanta
6|Jody|Ford|Chicago

汽车.txt

100|red|1
110|green|9
120|yellow|2
130|yellow|6
140|red|8
150|white|0

bash-4.3$ awk -F"|" 'NR==FNR { empcar[$1]=$0; next } { if (empcar[$3]) print empcar[$3] "|" $1 "|" $2 > "match.txt"; else print $0 > "no_match.txt" }' Employee.txt Car.txt
110|green|9
140|red|8
150|white|0

match.txt
1|Sam|Smith|Seatle|100|red
2|Barry|Jones|Seatle|120|yellow
6|Jody|Ford|Chicago|130|yellow

no_match.txt
110|green|9
140|red|8
150|white|0

bash-4.3$ awk -F"|" 'NR==FNR { empcar[$1]=$0; next } !($3 in empcar)' employee.txt car.txt produced the same list as in the no_match.txt.

但是,我希望 no_match.txt 如下:

3|Garry|Brown|Houston
4|George|Bla|LA
5|Celine|Wood|Atlanta

也就是说,打印Employee.txt中没有员工编号的行。在 Car.txt 中。我不知道如何在 else 语句中引用那些不匹配的记录。

我在 match.txt 中也遇到了很多无法解释的重复文件,其中包含无法披露的私人机密数据。

非常感谢, 乔治

【问题讨论】:

    标签: bash awk aix


    【解决方案1】:

    当没有员工编号时,打印Employee.txt 中的行。在Car.txt

    你可以使用这个解决方案:

    awk -F"|" '
    NR == FNR {
       empcar[$3]
       next
    }
    {
       print > ($1 in empcar ? "match.txt" : "no_match.txt")
    }' Car.txt Employee.txt
    
    cat match.txt
    
    1|Sam|Smith|Seatle
    2|Barry|Jones|Seatle
    6|Jody|Ford|Chicago
    
    cat no_match.txt
    
    3|Garry|Brown|Houston
    4|George|Bla|LA
    5|Celine|Wood|Atlanta
    

    请注意,我们将Car.txt 作为第一个文件进行处理,并将第三个字段中的所有 ID 存储在数组 empcar 中。稍后在处理Employee.txt 时,我们只是根据条件将输出重定向到匹配或不匹配,如果后面文件中的$1 存在于关联数组empcar 中。

    【讨论】:

    • 是的,阿努巴瓦。它工作得很好,我理解你的代码。这很简单。你能想到一些匹配的记录被重复甚至三次重复的可能性吗?不幸的是,无法共享我的数据,但匹配字符串是 ~7-8 个字母数字字符。已经非常感谢了。
    • 如果Employee.txt 有每个员工的唯一记录,则不会有任何重复。
    • 知道了。再次感谢。
    • 想知道我是否可以在最后一个关于这个主题的问题。除了员工#匹配之外,如何包括另一个条件,是在打印之前检查员工是否在 Employee.txt 中是当前/活动的(新的“状态”列)。同样,仅在 Car.txt 中包含具有可用颜色的汽车(新的“可用性”列)。再次感谢。
    • @GeorgeJackson:最好发布一个带有数据示例的新问题,以便我更好地理解并回答。
    猜你喜欢
    • 2020-04-16
    • 2021-06-15
    • 2012-10-18
    • 2021-09-24
    • 2021-09-23
    • 2016-07-30
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多