1,对于文件中的字符是以换行结尾的如下:
[root@py test]# cat 1.txt
11
22
aa
33
cc
[root@py test]# cat 2.txt
11
cc
dd
ee
ff
使用如下
[root@py test]# cat 2.sh
while read line1
do
while read line2
do
if [ $line1 = $line2 ]
then
echo $line1
fi
done <1.txt
done <2.txt
[root@py test]# ./2.sh
11
cc
2.如果文本文件是以空格或者制表符分隔的,如下:
[root@py ~]# cat 1.txt
aa bb cc dd ee
[root@py ~]# cat 2.txt
11 22 bb 33 44 dd
可以使用如下方法:
for i in `cat 1.txt`
do
for j in `cat 2.txt`
do
if [ $i = $j ]
then
echo $i
fi
done
done
bb
dd
当然这个方法也可以针对第一种方法,但是貌似效率没有第一种方法高.!
3.对于以其他分隔符分隔的,可以使用awk先来过滤,例如以
[root@py ~]# cat 1.txt
aa,bb,cc,dd,ee
[root@py ~]# cat 2.txt
11,22,bb,33,44,dd
for x in `awk -F, '{for(i=1;i<=NF;i++){print $i}}' 1.txt`
do
for y in `awk -F, '{for(i=1;i<=NF;i++){print $i}}' 2.txt`
do
if [ $x = $y ]
then
echo $x
fi
done
done
bb
dd