Created
April 5, 2018 19:51
-
-
Save RobertKrawitz/4cb7a6f2cd763f63c16994cf068839fc to your computer and use it in GitHub Desktop.
Extract range of lines in a file encompassing pattern match
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.