Skip to content

Instantly share code, notes, and snippets.

@purplexa
Last active October 29, 2015 00:17
Show Gist options
  • Select an option

  • Save purplexa/32be6c974d976c4c0c87 to your computer and use it in GitHub Desktop.

Select an option

Save purplexa/32be6c974d976c4c0c87 to your computer and use it in GitHub Desktop.
Use grep to print lines between two regular expressions
function grep_between () {
if [ -z $1 -o -z $2 -o -z $3 ]; then
echo "Usage:\ngrep_between 'starting regex' 'ending regex' file1 [file2 file3 ...]"
exit 2
fi
startregex=$1
endregex=$2
for i in ${@:3}; do
start="$(grep -n -m1 "$startregex" $i)"
if [ -n "$start" ]; then
startl="$(cut -d':' -f1 <<< $start)"
end="$(tail -n +$(( $startl + 1 )) $i | grep -n -m1 "$endregex")"
if [ -n "$end" ]; then
endl="$(( $(cut -d':' -f1 <<< $end) + $startl -1 ))"
echo "\n--\n$i:"
sed -n -e "${startl},${endl}p" $i
else
tail -n +$startl $i
fi;
fi;
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment