Skip to content

Instantly share code, notes, and snippets.

@su-tiko
Created March 27, 2019 09:39
Show Gist options
  • Save su-tiko/f39a1982976e7330a7258dbfefcc490d to your computer and use it in GitHub Desktop.
Save su-tiko/f39a1982976e7330a7258dbfefcc490d to your computer and use it in GitHub Desktop.
Grep all lines from the first to the last occurrence of a pattern in a file
# !/bin/bash
#
# greplines.sh
# Grep all lines from first to last occurrence of <pattern> in <file>
#
if [ "$#" -lt 2 ]; then
echo "usage: $0 <pattern> <file> [-v]"
exit
fi
pattern=$1
fileName=$2
verbose=$3
initialLine=$(grep -n "$pattern" $fileName | head -n1 | cut -d':' -f1)
endLine=$(grep -n "$pattern" $fileName | tail -n1 | cut -d':' -f1)
sed "$initialLine,$endLine!d" $fileName
if [ "$verbose" = "-v" ]; then
echo ""
echo "[+] Pattern: $pattern"
echo "[+] Filename: $fileName"
echo "[+] Initial line: $initialLine"
echo "[+] End line: $endLine"
echo ""
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment