我想打印带有彩色关键字的日志。以前我用过:
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"
作为一个函数并且它可以工作。
现在我想提取颜色定义并将其放入名为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;
}
并像这样使用它
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
}
但现在它只打印caused by
红色。
如何定义一个函数来返回一个管道以通过管道连接到另一个函数?
答案1
只需简化您的print_in_color
功能:
print_in_color() {
local -r LINE="${1//\//\\\/}"
local -r color=$(get_color "$2")
local -r nocolor='\x1b[0m'
sed "s/\(${LINE}\)/${color}\1${nocolor}/g"
}
您不需要循环输入数据。该sed
命令接受管道输入上的数据并将结果写入管道输出,以便您可以链接多个print_in_color
调用
更新
无get_color
功能:
#! /bin/bash
declare -g -r ANSI_CSI="\x1b["
declare -g -r ANSI_RESET="${ANSI_CSI}0m"
declare -g -r -A H_COLORS=(
[RED]="${ANSI_CSI}31m"
[GREEN]="${ANSI_CSI}32m"
[YELLOW]="${ANSI_CSI}33m"
[BLUE]="${ANSI_CSI}34m"
[PURPLE]="${ANSI_CSI}35m"
[OTHER]="${ANSI_CSI}38m"
)
# $1 string, $2 color(RED, YELLOW, BLUE, GREEN, PURPLE)
print_in_color() {
local -r LINE="${1//\//\\\/}"
local -r COLOR=${H_COLORS[${2:-OTHER}]}
sed "s/\(${LINE}\)/${COLOR:-${H_COLORS[OTHER]}}\1${ANSI_RESET}/g"
}