Skip to content

Instantly share code, notes, and snippets.

@wytten
Last active January 23, 2020 14:40
Show Gist options
  • Save wytten/57babe6dd13dc8fea8a9a03e6dab265a to your computer and use it in GitHub Desktop.
Save wytten/57babe6dd13dc8fea8a9a03e6dab265a to your computer and use it in GitHub Desktop.
bash function to print a range of lines defined by first and last occurrence of a pattern (e.g., dated log messages)
function ranger {
# print a range of lines defined by first and last occurence of pattern
local pattern="$1" && shift
local file="$1" && shift
if [ -z "$file" ] || [ $# -gt 0 ]; then
echo "Must specify one file exactly" >&2
return 1
fi
if [ ! -f "$file" ]; then
echo "$file: No such file or directory" >&2
return 1
fi
local num1=$(grep -n "$pattern" "$file" | head -1 | awk -F: '{ print $1 }' )
if [ -z "$num1" ]; then
echo "$pattern does not appear in $file" >&2
return 1
fi
local num2=$(grep -n "$pattern" "$file" | tail -1 | awk -F: '{ print $1 }' )
sed -n "$num1,${num2}p" "$file"
}
function today {
local today=$(/bin/date +"%Y-%m-%d")
ranger "^$today" "$@"
}
@wytten
Copy link
Author

wytten commented Jan 22, 2020

Q: How many exceptions were logged today in catalina.out?
A: today catalina.out | grep -c Exception:

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