I want to print logs with colored keywords. Previously I used:
cd ~/Code/Docker/somerepo && docker-compose logs -f my_service \
| grep -v "Successfully connected" \
| grep -v "this operation breaks ==" \
| sed "s/at com\.example\.product/at \x1b[32mcom\.example\.product\x1b[0m/g" \
| sed "s/caused by/\x1b[31mcaused by\x1b[0m/g"
as a function and it works.
Now I want to extract the color definition and put it into a function named get_color and print_in_color:
get_color() {
number=
case "$1" in
RED)
number='31'
;;
GREEN)
number='32'
;;
YELLOW)
number='33'
;;
BLUE)
number='34'
;;
PURPLE)
number='35'
;;
*)
number='38'
;;
esac
echo '\x1b['$number'm'
}
# $1 string, $2 color(RED, YELLOW, BLUE, GREEN, PURPLE)
print_in_color() {
while read data;
do
color=$(get_color $2)
nocolor='\x1b[0m'
echo $1 | sed "s/$1/${color}$1${nocolor}/g"
done;
}
And use it like
log_color() {
cd ~/Code/Docker/somerepo && docker-compose logs -f my_service \
| grep -v "Successfully connected" \
| grep -v "this operation breaks ==" \
| print_in_color 'com\.example\.product' BLUE \
| print_in_color 'caused by' RED
}
But now it only prints caused by in red.
How could I define a function to return a pipe to pipe into another function?