Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stop grep creating empty file if no results

Tags:

grep

bash

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?

like image 635
Alex Avatar asked Dec 08 '22 17:12

Alex


2 Answers

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
like image 72
9Breaker Avatar answered Jan 06 '23 07:01

9Breaker


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
  • grep should generate a non-zero return code for an empty output
  • quote the rm command to ensure not calling any aliases
  • use the -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 #1
like image 22
markp-fuso Avatar answered Jan 06 '23 08:01

markp-fuso