Untitled

 avatar
unknown
batchfile
a year ago
1.9 kB
3
Indexable
#!/bin/bash



# Inicjalizacja zmiennych domyślnych

word=""

min_lines=10

count_lines=false

file_list=""



# Funkcja wyświetlająca pomoc

show_help() {

    echo "Usage: $0 [-h] [-n <number>] [-c] [-l <file_list>] <word>"

    echo "Options:"

    echo "  -h            Display this help message"

    echo "  -n <number>   Minimum number of lines containing the word (default: 10)"

    echo "  -c            Display the count of lines containing the word for each file"

    echo "  -l <file_list> Process files listed in the specified file"

    exit 1

}



# Parsowanie opcji

while getopts ":hn:cl:" opt; do

    case $opt in

        h)

            show_help

            ;;

        n)

            min_lines=$OPTARG

            ;;

        c)

            count_lines=true

            ;;

        l)

            file_list=$OPTARG

            ;;

        \?)

            echo "Invalid option: -$OPTARG" >&2

            show_help

            ;;

        :)

            echo "Option -$OPTARG requires an argument." >&2

            show_help

            ;;

    esac

done



# Ustawienie zmiennej word na pozostały argument (słowo do szukania)

shift $((OPTIND - 1))

if [ -z "$1" ]; then

    echo "Error: Missing required argument <word>." >&2

    show_help

fi

word="$1"



# Funkcja przetwarzająca pojedynczy plik

process_file() {

    file="$1"

    lines_count=$(grep -c "$word" "$file")

    

    if [ "$lines_count" -ge "$min_lines" ]; then

        echo "$file"

        

        if [ "$count_lines" = true ]; then

            echo "  Lines containing '$word': $lines_count"

        fi

    fi

}



# Wywołanie funkcji dla każdego pliku

if [ -n "$file_list" ]; then

    while IFS= read -r file; do

        process_file "$file"

    done < "$file_list"

else

    find . -type f -exec grep -l "$word" {} + | while read -r file; do

        process_file "$file"

    done

fi

Editor is loading...
Leave a Comment