I want a script that searches through a directory of htm-files and finds all the files that have a given word.
Here’s a bash script that searches through a directory for HTML files containing a given word:
#!/bin/bash
# Check for proper usage
if [[ $# -ne 2 ]]; then
echo "Usage: $0 <directory> <word>"
exit 1
fi
# Assign variables
directory=$1
word=$2
# Find all .htm or .html files in the specified directory and search for the word
find "$directory" -type f \( -name "*.htm" -o -name "*.html" \) -exec grep -li "$word" {} \;
Explanation
$1
and$2
are positional arguments.$1
is the directory to search, and$2
is the word to look for.find
searches for.htm
or.html
files in the specified directory.grep -li
searches each file for the word (case-insensitive-i
), and outputs the file name only if a match is found (-l
).
Usage
Save this script (e.g., as find_word_in_html.sh
), make it executable, and run it as follows:
chmod +x find_word_in_html.sh
./find_word_in_html.sh /path/to/directory "search_word"
This will output the paths of all .htm
or .html
files in the specified directory containing the search word.
Also, I’d like to open the resulting files in my default browser.
You can modify the script to open each resulting file in the default browser. Here’s an updated version of the script that does this:
#!/bin/bash
# Check for proper usage
if [[ $# -ne 2 ]]; then
echo "Usage: $0 <directory> <word>"
exit 1
fi
# Assign variables
directory=$1
word=$2
# Find all .htm or .html files in the specified directory and search for the word
matching_files=$(find "$directory" -type f \( -name "*.htm" -o -name "*.html" \) -exec grep -li "$word" {} \;)
# Check if any files were found
if [[ -z "$matching_files" ]]; then
echo "No files found containing the word '$word'."
exit 0
fi
# Loop through each matching file and open it in the default browser
for file in $matching_files; do
xdg-open "$file" &> /dev/null &
done
echo "Opened files containing the word '$word' in the default browser."
Explanation
matching_files
stores the list of files found that contain the word.- If no files match, it displays a message and exits.
- For each matching file,
xdg-open
is used to open the file in the default browser (works on most Linux distributions).
Usage
Run the script as before:
./find_word_in_html.sh /path/to/directory "search_word"
This version will find files containing the specified word and open them in the default browser automatically.