0

How to find all files within folder containing specific text (string) if text found return 1 if not return 0 in linux?

grep -r "34161FA8203289722240CD40" /usr/lib/cgi-bin/ParkingSoft/api/v3/LaneApi/ETC/MywebSocket /*.txt
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • Do you want a shell script or javascript or an API? – Gaurav Pathak Dec 31 '22 at 11:39
  • Do you want all files containing `34161FA8203289722240CD40` or only text files? Do you want the list of files to be returned or do you want to return 1 if text found and return 0 if not? – Gaurav Pathak Dec 31 '22 at 11:39
  • `if text found return 1` - if text found in 1 file or in all files or something else? Whole line or whole word or partial matching? There are no "returns" in shell, just output and exit status - do you want to output 1 or exit with status 1? If it's 1 exit status - that's very counter-intuitive since `0` is the normal success exit status, as used by grep if it finds a match. – Ed Morton Dec 31 '22 at 18:38

2 Answers2

1

Try This:

grep -rwl 'PATH/targetFolder/' -e 'target_string' | awk -F "/" '{print $NF}'

The above command returns the name of all files that contains the target_string.

To know about -rwl check this answer, However awk -F "/" '{print $NF}' just split the grep output and return the last part. (file name in your case)

Niyaz
  • 797
  • 1
  • 8
  • 18
0

The -q option returns (exit code) 1 when no match is found. Try:

echo "string" | grep -q in && echo yes
echo "string" | grep -q out && echo yes

In your case:

searchdir="/usr/lib/cgi-bin/ParkingSoft/api/v3/LaneApi/ETC/MywebSocket "
if [ ! -d "$searchdir" ]; then
  echo "Check searchdir. Is 'ETC' really in uppercase and is `Mywebsocket ` including a space?"
else
  if grep -rwq '34161FA8203289722240CD40' "${searchdir}/*.txt; then
    echo "String found in one of the files."
  fi
fi
Walter A
  • 19,067
  • 2
  • 23
  • 43