IdelHamza IdelHamza - 8 days ago 5
Bash Question

The existence of more than one word given in parameter, in files content?

I'm trying to find a command on bash shell, which allows me to verify if all words given in parameter(in the list

$*
), exist in the current directory I'm in.

Exemple, if I execute this command:

bash ./exp_quotes.sh hadir Trex blabla


How to test the existence of the tree words in one command, and get a value of 1 or 0 as
$?
?

Answer

You can make grep do all the job of searching for all patterns.
You just need to concatenate all of them toghetehr with |, as this:

$ echo "$(IFS=\|; echo "$*")"
hadir|Trex|blabla

Then, you just need to use grep to do the search:

$ cat ./exp_quotes.sh
#!/bin/bash
file="$1"
grep -qE "\"$(IFS=\|; echo "$*")\"" "$file" && exit 1 || exit 0

Change the permisions (to run) of the script:

$ chmod u+x ./exp_quotes.sh

And execute it with the filename first and the patterns:

$ ./exp_quotes.sh file hadir Trex blabla

This may be used even for patterns with spaces:

$ ./exp_quotes.sh "file name with spaces" "a hadir with spaces"  Trex blabla

If what you need is to list the files that do contain all the words, use this:

$ cat ./exp_quotes.sh

#!/bin/bash
grep -lE "\"$(IFS=\|; echo "$*")\"" *