Created
November 9, 2023 09:22
-
-
Save basu021/24ae191bc05ce65b57597fba3fe87f78 to your computer and use it in GitHub Desktop.
This script accepts the following options: -d: Specify the directory to start the search (default is the current directory). -e: Specify file extensions separated by commas. -o: Specify search options (default is to recursively search in subdirectories). The script also accepts multiple search texts as arguments, separated by spaces. bash script…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Define the directory to start the search | |
SEARCH_DIR="." | |
# Define default file extensions and search options | |
FILE_EXTENSIONS=("txt") | |
SEARCH_OPTIONS="-r" # Default: recursively search in subdirectories | |
# Parse command line arguments | |
while getopts "d:e:o:" opt; do | |
case $opt in | |
d) | |
SEARCH_DIR="$OPTARG" | |
;; | |
e) | |
IFS=',' read -ra FILE_EXTENSIONS <<< "$OPTARG" | |
;; | |
o) | |
SEARCH_OPTIONS="$OPTARG" | |
;; | |
\?) | |
echo "Invalid option: -$OPTARG" >&2 | |
exit 1 | |
;; | |
esac | |
done | |
# Shift to process non-option arguments (search texts) | |
shift $((OPTIND-1)) | |
SEARCH_TEXTS=("$@") | |
# Use find and grep to search for text in files with specified extensions | |
for ext in "${FILE_EXTENSIONS[@]}"; do | |
find "$SEARCH_DIR" $SEARCH_OPTIONS -type f -name "*.$ext" | while read -r file; do | |
# Use grep to check if any of the search texts are present in the file | |
for search_text in "${SEARCH_TEXTS[@]}"; do | |
if grep -q "$search_text" "$file"; then | |
echo "Text '$search_text' found in file: $file" | |
fi | |
done | |
done | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
bash script.sh -d /path/to/search -e txt,log -o -r hello "hello world"