I'm comparing the results of two files for lines in one that are not in the other using grep -v -f file1.txt file2.txt > result.txt
Let's say my files look like;
file1.txt
alex
peter
zoey
file2.txt
alex
john
peter
zoey
So result.txt
should contain john
This is to be run inside a Jenkins job, and jenkins ends up not happy with creating an empty result.txt
if there are no differences between the two.
I can't just do a blind diff/no diff output, I specifically need to know which lines differ if there are any.
Is there a neater way to run this command to not create a file if there are no results?
EDIT: Try conditionally running the command with the quiet option -q (which will exit when one match is found and save time). Then once the first match is found (meaning the files are different), you will run the same command and output it to your file.
Try this: (EDIT taken from Charles Duffy's comment)
#!/usr/bin/env bash
if grep -qvf file1.txt file2.txt
then
grep -vf file1.txt file2.txt > output.txt
echo "Differences exist. File output.txt created."
else
echo "No difference between the files detected"
fi
Or with less code and one line:
grep -qvf file1.txt file2.txt && grep -vf file1.txt file2.txt > output.txt
Could you do something as simple as removing the file if it's empty?
Solution #1:
grep -v -f file1.txt file2.txt > result.txt
[[ $? -ne 0 ]] && 'rm' -f result.txt
rm
command to ensure not calling any aliases-f
to keep silent any messages should the file not exist (shouldn't happen, but doesn't hurt to code for this anyway)Solution #2:
grep -v -f file1.txt file2.txt > result.txt
[[ ! -s result.txt ]] && 'rm' -f result.txt
-s
=> file exists and is greater than 0 in size! -s
=> file doesn't exist or file exists and is 0 in size'rm' -f
... same explanation as for solution #1If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With