0

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?

metters
  • 533
  • 1
  • 8
  • 17
nmr
  • 605
  • 6
  • 20
  • 2
    Possible duplicate of [Compare two files line by line and generate the difference in another file](https://stackoverflow.com/q/4544709/608639), [How to check if a file is empty in Bash?](https://stackoverflow.com/q/9964823/608639), [How to pipe output from one process to another but only execute if the first has output?](https://unix.stackexchange.com/q/13326), etc. – jww May 28 '19 at 01:33
  • @jww Thank you for your comment 1) I have compared files in my code 2) I am not looking to find if any file is empty. I basically don't want to create a empty file while comparing two files – nmr May 28 '19 at 02:21
  • 2
    Check `man diff` – Robert May 28 '19 at 02:34

1 Answers1

1

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
KamilCuk
  • 120,984
  • 8
  • 59
  • 111