linux两个文件下一行行对比,输出内容完全相同的行

需求

两个文件一行行对比,输出内容完全相同的行或者内容不同的行

方法

  • 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

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

格桑8

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值