#!/bin/bash
[ "$2" == "" ] && exec echo "Usage: $0 <FILENAME> <SEARCH_STRING>"
# Usage: ./string_occurrence.sh <filename> <search_string>

FILE="$1"
SEARCH="$2"

if [[ ! -f "$FILE" ]]; then
    echo "File not found: $FILE"
    exit 1
fi

if [[ -z "$SEARCH" ]]; then
    echo "Search string is empty."
    exit 1
fi

# Count total occurrences (ignore case)
OCCURRENCE_COUNT=$(grep -io "$SEARCH" "$FILE" | wc -l)

# Find line numbers (ignore case)
LINE_NUMBERS=$(grep -in "$SEARCH" "$FILE" | cut -d: -f1 | sort -n | uniq)

echo "Search string: \"$SEARCH\""
echo "File: $FILE"
echo "Total occurrences: $OCCURRENCE_COUNT"
echo "Found on lines: $LINE_NUMBERS"

echo ""
echo "Matched lines:"
grep -in "$SEARCH" "$FILE" | while IFS=: read -r LINENUM LINECONTENT; do
    echo "[$LINENUM] $LINECONTENT"
done
