-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhl
executable file
·105 lines (92 loc) · 1.9 KB
/
hl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/usr/bin/env bash
# ./hl
#
# color highlight by regexp pattern from stdin
#
# see --help for usage
#
# example:
# echo -e "line1: SUCCESS cmd\nline2: FAIL test" | hl -bg red -fg white FAIL | hl -fg green -b SUCCESS
# ./PROGRAM | hl -bg red -fg white FAIL | hl -fg green -b SUCCESS
# cat /path/to/log | hl -bg r -l ERROR
# tail -f /path/to.log | hl -bg r -m Error
#
# author: @qbbr
fg=""
bg=""
bold=""
line=""
i="i"
reset=$(tput sgr0)
usage() {
echo "Usage: ${0##*/} [option] [argument] pattern"
echo
echo "Options:"
echo " -bg - set background color"
echo " -fg - set foreground color"
echo " -b, --bold - set bold text"
echo " -l, --line - highlight all line"
echo " -m, --match-case - match case distinctions (default: ignore case)"
echo " -h, --help - display this help and exit"
exit 0
}
color_name_to_number () {
case $1 in
bla*) echo 0;; # black
r*) echo 1;; # red
g*) echo 2;; # green
y*) echo 3;; # yellow
b*) echo 4;; # blue
m*) echo 5;; # magenta
c*) echo 6;; # cyan
w*) echo 7;; # white
*) echo 0;;
esac
}
POSITIONAL=()
while [[ $# -gt 0 ]]; do
key="$1"
case ${key} in
-fg)
fg="$2"
shift # past argument
shift # past value
;;
-bg)
bg="$2"
shift
shift
;;
-b|--bold)
bold="$(tput bold)"
shift # past argument
;;
-l|--line)
line=".*"
shift
;;
-m|--match-case)
i=""
shift
;;
-h|--help)
usage
;;
*) # unknown option
POSITIONAL+=("$1") # save it in an array for later
shift
;;
esac
done
set -- "${POSITIONAL[@]}" # restore positional parameter
pattern="$*"
if [[ -n "${fg}" ]]; then
fg=$(tput setaf $(color_name_to_number ${fg}))
fi
if [[ -n "${bg}" ]]; then
bg=$(tput setab $(color_name_to_number ${bg}))
fi
if [[ -z "${fg}${bg}" ]]; then
bg=$(tput smso)
fi
sed "s/${line}${pattern}${line}/${bold}${fg}${bg}&${reset}/g${i}"