1

I have 2 files - file1.txt and file2.txt. I want to set a condition such that, a command is run on both files only if a pattern "xyz" is present in both files. Even if one file fails to have that pattern, the command shouldn't run. Also , I need to have both files being passed to the grep or awk command at the same time as I am using this code inside another workflow language. I wrote some code with grep, but this code performs the action even if the pattern is present in one of the files, which is not what I want . Please let me know if there is a better way to do this.

if grep "xyz" file1.txt file2.txt; then
     my_command file1.txt file2.txt 
else 
     echo " command cannot be run on these files"
fi 

Thanks!

Cyrus
  • 84,225
  • 14
  • 89
  • 153
rkm19
  • 149
  • 1
  • 7
  • 1
    This might help: [How to get the exit status of multiple parallel background processes in bash](https://stackoverflow.com/q/46193327/3776858) – Cyrus Oct 21 '20 at 05:49

2 Answers2

1

This awk should work for you:

awk -v s='xyz' 'FNR == NR {
   if ($0 ~ s) {
      ++p
      nextfile
   }
   next
}
FNR == 1 {
   if (!p) exit 1
}
{
   if ($0 ~ s) {
      ++p
      exit
   }
}
END {
   exit p < 2
}' file1 file2

This will exit with 0 if given string is found in both the files otherwise it will exit with 1.

anubhava
  • 761,203
  • 64
  • 569
  • 643
1

Salvaging code from a deleted answer by Cyrus:

if grep -q "xyz" file1.txt && grep -q "xyz" file2.txt; then
  echo "xyz was found in both files"
else
  echo "xyz was found in one or no file"
fi

If you need to run a single command, save this as a script, and run that script in your condition.

#!/bin/sh
grep -q "xyz" "$1" && grep -q "xyz" "$2"

If you save this in your PATH and call it grepboth (don't forget to chmod a+x grepboth when you save it) your condition can now be written

grepboth file1.txt file2.txt

Or perhaps grepall to accept a search expression and a list of files;

#!/bin/sh
what=$1
shift
for file; do
    grep -q "$what" "$file" || exit
done

This could be used as

grepall "xyz" file1.txt file2.txt
tripleee
  • 175,061
  • 34
  • 275
  • 318