Skip to content

Instantly share code, notes, and snippets.

@basu021
Created November 9, 2023 09:22
Show Gist options
  • Select an option

  • Save basu021/24ae191bc05ce65b57597fba3fe87f78 to your computer and use it in GitHub Desktop.

Select an option

Save basu021/24ae191bc05ce65b57597fba3fe87f78 to your computer and use it in GitHub Desktop.

Revisions

  1. basu021 created this gist Nov 9, 2023.
    43 changes: 43 additions & 0 deletions search_text.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    #!/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