比较awk中文件的值

时间:2014-04-09 07:36:20

标签: shell awk

我有两个名为file1和file2的文件,现在我想从file1中选择值并在整个file2上搜索它,如果找到了记录,则对file1记录应用操作,否则对file1记录应用其他一些操作。

档案1

a
s
d
f
g

文件2

q
e
r
a
g

早些时候我正在使用如下

awk -F'|' '{if($1="abc" || $1="a") print ......}' file1 

现在我有多个要比较的值,我已将值放在文件中(abc,a .....) 但我不知道如何使用它。

请帮忙

2 个答案:

答案 0 :(得分:0)

执行此操作的常用方法是将要搜索的值存储在哈希中,并将其用作查找表。这样的事可能适合你:

search.awk

FNR==NR { 
  seen[$0]
  next
}

$0 in seen { 
  print $0 " is in file2"
  next 
} 

{ 
  print $0 " is not in file2" 
}

像这样运行:

awk -f search.awk file2 file1

输出:

a is in file2
s is not in file2
d is not in file2
f is not in file2
g is in file2

答案 1 :(得分:0)

使用awk

awk 'NR==FNR{a[$1];next}{print $0,($1 in a)?"Yes":"No"}' file2 file1

a Yes
s No
d No
f No
g Yes