You can try this script:
#!/bin/bash
shopt -s extglob
SEARCHDIR_DEFAULT="./"
read -ep "Enter search directory [$SEARCHDIR_DEFAULT]: " SEARCHDIR
[[ $SEARCHDIR =~ ^[[:space:]]*$ ]] && SEARCHDIR=$SEARCHDIR_DEFAULT
for (( ;; )); do
read -p "Enter search item: " SEARCHITEM
read -p "Enter number of lines to display: " NUMLINES
readarray -t MATCHEDFILES < <(exec grep -rl "$SEARCHITEM" "$SEARCHDIR")
echo "Please select a file to search into. Press C to cancel, or X to exit."
select FILE in "${MATCHEDFILES[@]}"; do
if [[ -n $FILE ]]; then
readarray -t MATCHEDLINES < <(exec grep -n "$SEARCHITEM" "$FILE")
echo "Please select starting line."
select LINE in "${MATCHEDLINES[@]}"; do
if [[ -n $LINE ]]; then
LINENUM=${LINE%%:*}
tail -n "+$LINENUM" "$FILE" | head -n "$NUMLINES"
elif [[ $REPLY == [cC] ]]; then
break
elif [[ $REPLY == [xX] ]]; then
break 3
fi
done
elif [[ $REPLY == [cC] ]]; then
break
elif [[ $REPLY == [xX] ]]; then
break 2
fi
done
done
New version:
#!/bin/bash
shopt -s extglob
SEARCHDIR_DEFAULT="./"
NUMLINES_DEFAULT=10
for (( ;; )); do
until
read -ep "Enter search directory [$SEARCHDIR_DEFAULT]: " SEARCHDIR
[[ $SEARCHDIR =~ ^[[:space:]]*$ ]] && SEARCHDIR=$SEARCHDIR_DEFAULT
[[ -d $SEARCHDIR ]]
do
echo "Please enter a valid directory."
done
SEARCHDIR_DEFAULT=$SEARCHDIR
until
read -p "Enter search item: " SEARCHITEM
[[ ! $SEARCHITEM =~ ^[[:blank:]]*$ ]]
do
echo "Please enter a valid search item."
done
until
read -p "Enter number of lines to display [$NUMLINES_DEFAULT]: " NUMLINES
[[ $NUMLINES =~ ^[[:space:]]*$ ]] && NUMLINES=$NUMLINES_DEFAULT
[[ $NUMLINES =~ ^[[:digit:]]+$ && NUMLINES -gt 0 ]]
do
echo "Please enter a valid number of lines."
done
NUMLINES_DEFAULT=$NUMLINES
readarray -t MATCHEDFILES < <(exec grep -rle "$SEARCHITEM" "$SEARCHDIR")
P1="Please select a file to search into. [ENTER = show list again, C = cancel, X = exit]: "
P2="Please select starting line. [ENTER = show list again, C = cancel, X = exit]: "
PS3=$P1
select FILE in "${MATCHEDFILES[@]}"; do
if [[ -n $FILE ]]; then
readarray -t MATCHEDLINES < <(exec grep -ne "$SEARCHITEM" "$FILE")
if [[ ${#MATCHEDLINES[@]} -eq 0 || ! ${MATCHEDLINES[0]} =~ ^[[:digit:]]+: ]]; then
echo "No matching lines were extracted. Perhaps file is a binary."
elif [[ ${#MATCHEDLINES[@]} -eq 1 ]]; then
LINENUM=${MATCHEDLINES[0]%%:*}
echo "----------------------------------------"
tail -n "+$LINENUM" "$FILE" | head -n "$NUMLINES"
echo "----------------------------------------"
else
PS3=$P2
select LINE in "${MATCHEDLINES[@]}"; do
if [[ -n $LINE ]]; then
LINENUM=${LINE%%:*}
echo "----------------------------------------"
tail -n "+$LINENUM" "$FILE" | head -n "$NUMLINES"
echo "----------------------------------------"
elif [[ $REPLY == [cC] ]]; then
break
elif [[ $REPLY == [xX] ]]; then
break 3
fi
done
PS3=$P1
fi
elif [[ $REPLY == [cC] ]]; then
break
elif [[ $REPLY == [xX] ]]; then
break 2
fi
done
done