Skip to content

Instantly share code, notes, and snippets.

@bartman
Last active August 29, 2015 14:17
Show Gist options
  • Save bartman/8fa33b453cb942fbea34 to your computer and use it in GitHub Desktop.
Save bartman/8fa33b453cb942fbea34 to your computer and use it in GitHub Desktop.
#!/bin/bash
# 2015 (C) [email protected]
# loosly based on
# https://github.com/kepkin/dev-shell-essentials
set -e
self=$(basename $0)
fg_colors=( red green yellow blue magenta cyan )
autocolor=
context=
use_pager=
declare -A fg_color_map
fg_color_map[black]=30
fg_color_map[red]=31
fg_color_map[green]=32
fg_color_map[yellow]=33
fg_color_map[blue]=34
fg_color_map[magenta]=35
fg_color_map[cyan]=36
function highlight() {
local col="$1"
local pat="$2"
local fg_c="$(echo -e "\e[1;${fg_color_map[$col]}m")"
local c_rs=$'\e[0m'
#while read -r line; do echo $line | sed s"/$pat/$fg_c\0$c_rs/"; done
sed -ure s"/$2/$fg_c\0$c_rs/g"
}
function show_help() {
exit_with=$1
cat <<END
$self -h
$self [ <col> <pattern> ] ...
$self -a [ <pattern> ] ...
-h - this help
-a - auto color assignment
-C<num> - pass input through grep -C first to limit the context
-p - paginate through \$PAGER
END
exit $exit_with
}
while [[ ${1:0:1} = '-' ]] ; do
case "$1" in
-h) show_help ;;
-a) autocolor=0 ;;
-p) use_pager="$PAGER" ;;
-C[0-9]*) context="${1:2}" ;;
-C) shift ; context="$1" ;;
esac
shift
done
if [[ -z "$1" ]] ; then
show_help 1
fi
grep_cmd=()
cmd=()
sep=
while [[ -n "$1" ]] ; do
if [[ -z "$autocolor" ]] ; then
col="$1" ; shift
else
col=${fg_colors[$autocolor]}
autocolor=$(($autocolor+1))
[[ $autocolor > ${#fg_colors[*]} ]] && autocolor=0
fi
pat="$1" ; shift
cmd=( "${cmd[*]}" $sep highlight "$col" "$pat" )
sep='|'
if [[ -n "$context" ]] ; then
grep_cmd=( "${grep_cmd[*]}" -e "$pat" )
fi
done
if [[ -n "$context" ]] ; then
use_C=
[[ $context -gt 0 ]] && use_C=-C"$context"
cmd=( grep --line-buffered -E $use_C "${grep_cmd[*]}" '|' "${cmd[*]}" )
fi
if [[ -n "$use_pager" ]] ; then
cmd=( "${cmd[*]}" '|' "$use_pager" )
fi
#echo "${cmd[*]}"
#exit 0
eval "${cmd[*]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment