linuxbashcomm

compare two files and store the output in a file only if there is a mismatch


I am comparing multiple files in a while loop and storing the output in new files.

I am doing like below

while IFS='|' read -r work_table_name final_table_name;do
    comm -23 <(sort /home/$USER/work_schema/${work_table_name}_work_schema.txt) <(sort /home/$USER/final_schema/${final_table_name}_final_schema.txt) > /home/$USER/mismatched_schema/${final_table_name}.txt
done < /home/$USER/tables.txt   

I am getting what I want. But just need a bit of result of the whole while loop.

I want to create files only when there is a mismatch between the files. If there is no mismatch then don't create a file at all.

How can I achieve that?


Solution

  • But just need a bit of result of the whole while loop.

    So redirect the whole while loop output:

    while read -r ....; do
        comm -23 <(...) <(...)
    done < input > output
    

    Or append:

    # this will truncate the output file, so we start empty
    : > output 
    
    while read -r ....; do
         comm -23 <(...) <(...) >> output
    done < input
    

    I basically don't want to create a empty file while comparing two files

    So check if it's empty or not...

    out=$(comm -23 <(....) <(....))
    if ((${#out} != 0)); then
        printf "%s" "$out"
    fi