-
Notifications
You must be signed in to change notification settings - Fork 0
/
colorize.sh
executable file
·79 lines (63 loc) · 1.47 KB
/
colorize.sh
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
#!/usr/bin/env bash
# Adjust the default order of the colors here.
# First highlighted field will be colored in first
# color, second in second and so on.
COLORS=(
31 # RED
32 # GREEN
34 # BLUE
33 # YELLOW
35 # MAGENTA
36 # CYAN
)
############################
COLORS_LEN=${#COLORS[@]}
# Bash color code sequences
ESC_SEQ="\x1b["
COL_RESET=$ESC_SEQ"39;49;00m"
BG_SEQ=";01m"
function show_help {
echo "Example usage: $0 0,1,4"
echo "This colorizes the fields 0,1 and 4"
}
function containsElement () {
local e
for e in "${@:2}"
do
[[ "$e" == "$1" ]] && return 1
done
return 0
}
function colorize {
# Split the input string into tokens
IFS=' ' read -ra ARR <<< "$1"
# Check which field should be colored
IFS=',' read -ra FIELDS <<< "$2"
# Define the output
output=()
# For each token...
for i in "${!ARR[@]}"; do
token=${ARR[$i]}
# Is this a field that should be colored?
containsElement $i "${FIELDS[@]}"
if [ $? -eq 1 ]
then
# Yes. Colorize and store in output array
color=$(($i % $COLORS_LEN))
output+=($(echo -e "$ESC_SEQ${COLORS[$color]}$BG_SEQ$token$COL_RESET"))
else
# No. Just print the word.
output+=($(echo $token))
fi
done
# Print joined output array
( IFS=$' '; echo "${output[*]}" )
}
# Check if we got exactly one argument:
# the fields to be colored
if [ "$#" -ne 1 ]; then
show_help
exit
fi
# Colorize all the things!
while read -r line; do colorize "$line" $1; done