awk 有 2 个文件和 if 语句?

时间:2021-07-14 10:05:29

标签: awk

我一直在努力完成这项任务。

我有 2 个文件:

文件 1:

London
Milan
Paris

文件 2:

London

所需的输出文件:

London Present
Milan Absent
Paris Absent

本质上,任务很简单:我想重新打印文件 1(以完全相同的顺序)并添加一列,如果该术语存在于文件 2 中,则在其中我说“存在”,或者如果不存在则“不存在”。

我一直在尝试使用 awk,但我做不到。

1 个答案:

答案 0 :(得分:2)

好吧,这里有一个确切的 awk 来解决您的问题。希望能帮到你:

$ awk '
NR==FNR {                                   # process file2
    a[$1]                                   # hash first field
    next                                    # on to next record
}
{                                           # process file1
    print $1,(($1 in a)?"Present":"Absent") # print field and presense in a hash
}' file2 file1                              # mind the order

输出:

London Present
Milan Absent
Paris Absent

如果您文件中的单词有空格,请考虑将 $1s 更改为 $0s。