Skip to content

Instantly share code, notes, and snippets.

@RobertKrawitz
Created April 5, 2018 19:51
Show Gist options
  • Save RobertKrawitz/4cb7a6f2cd763f63c16994cf068839fc to your computer and use it in GitHub Desktop.
Save RobertKrawitz/4cb7a6f2cd763f63c16994cf068839fc to your computer and use it in GitHub Desktop.
Extract range of lines in a file encompassing pattern match
#!/bin/sh
# grep-interval -- extract range of lines including the first
# line matching the specified pattern, the last line matching
# the pattern, and all lines in between.
if (( $# != 2 )) ; then
echo "Usage: $0 pattern file" 1>&2
exit 1
fi
pattern=$1
file=$2
first=$(grep -n "$pattern" "$file"|head -1|cut -d: -f1)
[[ -z $first ]] && exit 0
last=$(grep -n "$pattern" "$file"|tail -1|cut -d: -f1)
tail -n +$((first)) "$file" |head -$((last-first+1))
@RobertKrawitz
Copy link
Author

Very useful for extracting lines from a log when you want to follow everything happening with respect an event, but there may be intermediate lines of interest that won't be caught with grep.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment