在Unix中查找另一个文件的内容

时间:2014-08-05 15:23:12

标签: bash file unix awk grep

我正在尝试在另一个文件(f2)中搜索一个文件(f1)的内容并打印成功的匹配。
我已经尝试了各种已发布的答案,如下所示,但没有一个有用。

1。
awk 'FNR==NR{a[$0]++}FNR!=NR && !a[$0]{print}' f1 f2

2。

while read name
do
awk '$1 ~ '$name'' f2| awk '{print $NF, $4}' >> f3
done < f1 

3。
grep -F -f f1 f2 > f3

以上所有解决方案也从f2打印非匹配条目。还有其他办法吗?

我期待在我的场景中完全匹配。 比如说

$ cat f1
ABC
高清
ghi

$ cat f2
这条线有abc
BC
ABC

这条线有ghi

ghi

预期产量:
ABC
ghi

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

尝试以下命令(-i)标志是搜索不区分大小写的

grep -i -Fx -f search_this.txt search_in.txt

演示会议在

之下
$ cat search_this.txt
xxxx yyyy
kkkkkk
zzzzzzzz

$ cat search_in.txt
line doesnot contain any name
This person is xxxx yyyy good
xxxx yyyy
Another line which doesnot contain any name
Is kkkkkk a good name ?
kkkkkk
This name itself is sleeping ...zzzzzzzz
I can't find any other name
Lets try the command now

$ grep -i -Fx -f search_this.txt search_in.txt
xxxx yyyy
kkkkkk

答案 1 :(得分:0)

对我而言,这是有效的,但我不确定这是否可以从变量扩展的角度来看是安全的

PATTERN=`cat f1`; pcregrep -M "$PATTERN" f2

为了使用f2作为应该找到的每个模式的数量,解决方案似乎在这里:finding contents of one file into another file in unix shell script