Unix command to find lines common in two files

前端 未结 11 1256
忘掉有多难
忘掉有多难 2020-11-27 10:32

I\'m sure I once found a unix command which could print the common lines from two or more files, does anyone know its name? It was much simpler than diff.

11条回答
  •  粉色の甜心
    2020-11-27 10:33

    Just for reference if someone is still looking on how to do this for multiple files, see the linked answer to Finding matching lines across many files.


    Combining these two answers (ans1 and ans2), I think you can get the result you are needing without sorting the files:

    #!/bin/bash
    ans="matching_lines"
    
    for file1 in *
    do 
        for file2 in *
            do 
                if  [ "$file1" != "$ans" ] && [ "$file2" != "$ans" ] && [ "$file1" != "$file2" ] ; then
                    echo "Comparing: $file1 $file2 ..." >> $ans
                    perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/' $file1 $file2 >> $ans
                fi
             done 
    done
    

    Simply save it, give it execution rights (chmod +x compareFiles.sh) and run it. It will take all the files present in the current working directory and will make an all-vs-all comparison leaving in the "matching_lines" file the result.

    Things to be improved:

    • Skip directories
    • Avoid comparing all the files two times (file1 vs file2 and file2 vs file1).
    • Maybe add the line number next to the matching string

提交回复
热议问题