需求
两个文件一行行对比,输出内容完全相同的行或者内容不同的行
方法
- while遍历两文件行,并比较
- for遍历两文件行,并比较
- grep匹配
- comm命令
while
file1=$1
file2=$2
cat $file1 | while read lineb
do
cat $file2 | while read linea
do
if [ "$lineb" = "$linea" ];then # 此处变量要加""引号,否则出问题
echo $lineb >>res
fi
done
done
for
IFS=$'\n' # 如果cat文件包含了空格这个分隔符,这里涉及到了shell的域分隔符即(IFS),默认是空格回车和tab,所以这里需要指定IFS,并在循环执行前解析,否则输出的是每行空格隔开的内容。而read是一行行读文件的,没有这个需求
for i in `cat $file1`;do
for j in `cat $file2`;do
if [[ "$i" == "$j" ]];then # 或者if [ "$i" = "$j" ];then
echo $i
fi
done
done
grep
for i in $(cat $file1);do # 此处不需要指定域分隔符IFS
grep "\<$i\>" $file2
done
comm
comm -12 file1 file2 # 该命令最快,最好用
comm命令用户手册manual:man comm
COMM(1) User Commands COMM(1)
NAME
comm - compare two sorted files line by line # 用于逐行比较两个已排过序的文件。
SYNOPSIS
comm [OPTION]... FILE1 FILE2 # 用法
DESCRIPTION
Compare sorted files FILE1 and FILE2 line by line.
With no options, produce three-column output. Column one contains lines unique to FILE1, column two contains lines unique
to FILE2, and column three contains lines common to both files. # 不带可选项产生3列
-1 suppress column 1 (lines unique to FILE1) # 单独出现在file1的行
-2 suppress column 2 (lines unique to FILE2) # 单独出现在file2的行
-3 suppress column 3 (lines that appear in both files) # 同时出现在file1和file2的行
--check-order # 检查输入是否正确排序
check that the input is correctly sorted, even if all input lines are pairable
--nocheck-order # 检查输入是否正确排序
do not check that the input is correctly sorted
--output-delimiter=STR # delimiter是分割符的意思,所以有些参数缩写-d就是分隔符的意思
separate columns with STR # 使用分割符
--help display this help and exit
--version
output version information and exit
Note, comparisons honor the rules specified by 'LC_COLLATE'.
EXAMPLES
comm -12 file1 file2
Print only lines present in both file1 and file2.
comm实例
参考:https://blog.csdn.net/weixin_42163563/article/details/92628240