0

I am trying to make the following into a bash script:

#!/bin/bash

find /path/to/file -type f -name "*.html" -exec grep -l "XXXX" '{}' \; -print

where XXXX is a list of strings over which this command should be looped. I struggle to make the correct portion of this script into a loop and I struggle to save the XXXX to a variable that will then be looped over.

0

If you just want to grep for any of the strings represented by XXXX in every .html file in that directory and return the files where any of the strings appear, then the following will be sufficient:

egrep -l "string1|string2|string3" /path/to/directory/*.html 

grep -El "string1|string2|string3" /path/to/directory/*.html

They both do the same but one uses egrep instead of grep -E. The -l switch returns the file that the string appears in and not the line containing it. If you really need to assign the strings to a variable:

export strings='string1|string2|string3'

egrep -l "$strings" /path/to/directory/*.html 

grep -El "strings" /path/to/directory/*.html
0

I you want to perform any operation on the files where strings are available use the below:

#!/bin/bash

declare -a STRINGS=$(find /var/www/html/ -type f -name "*.html" -exec grep "this is 
test" {} \; -print)

for string in "${STRINGS[@]}"
do
   echo "${string}"
    echo "${STRINGS}"

done

O/P:

[root@awx html]# sh test.sh
this is test file1
/var/www/html/1.html
this is test file2
/var/www/html/2.html
this is test file1
/var/www/html/1.html
this is test file2
/var/www/html/2.html
[root@awx html]#
0

You can use a file with the strings you want to look for:

file.txt

foo
bar

And then

find /path/to/file -type f -name "*.html" -exec grep -l -f file.txt '{}' \; -print

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.