Friday, May 27, 2022

[SOLVED] Regex/Grep to filter strings in text file

Issue

I need a regex/grep command for a text file with multiple strings in it and I want to return an error if there are strings other than String1 and String2. TIA!

String1... String2... String3... String4... etc

I tried the following but it doesn't seem to be as expected

if grep -v 'excel' document.txt | grep -v 'word'; then
  echo "error"
fi

Solution

You can use a single pattern matching either word or excel or an empty line using an alternation and check if there is a reversed result, and use --quiet to not write to standard output.

if grep --quiet -v 'word\|excel\|^[[:space:]]*$' document.txt; then
  echo "error"
fi


Answered By - The fourth bird
Answer Checked By - Cary Denson (WPSolving Admin)