Tre*_*ith 11 colors scripting bash shell-script
我正在运行一些单元测试代码。单元测试代码输出常规文本。有很多文本,所以我想为用户突出显示重要的关键字。
在这种情况下,关键字是“通过”和“失败”。
你如何将“通过”着色为绿色,将“失败”着色为红色?
supercat 似乎做你正在寻找的东西。
包装:超级猫 描述-zh: 为终端和 HTML 文本着色的程序 Supercat 是一个基于匹配正则对文本着色的程序 表达式/字符串/字符。Supercat 也支持 html 输出 作为标准 ASCII 文本。与某些文本着色程序不同 存在,Supercat 不需要您必须是程序员才能 制定着色规则。 主页:http://supercat.nosredna.net/
似乎没有任何方法可以告诉它在命令行上着色什么,您必须指定一个配置文件。
我似乎记得曾经有一个名为“hilite”或“hl”的程序,它突出显示与模式匹配的文本(例如grep --colour,但也显示不匹配的行),但我在搜索时找不到它。
最后,GNUgrep可用于突出显示图案 - 但只能使用一种颜色(即,您不能将 PASS 设为绿色,将 FAIL 设为红色,两者都将以相同的颜色突出显示)。
通过这样的方式管道您的数据:
egrep --color "\b(PASS|FAIL)\b|$"
Run Code Online (Sandbox Code Playgroud)
此示例使用 egrep(又名grep -E),但-G基本的正则表达式、-F固定字符串和-PPCRE 也可以使用。
所有匹配项都将突出显示。默认为红色,或设置 GREP_COLOR 环境变量。
这项工作的关键是|$模式中的最终匹配行尾(即所有行匹配),因此将显示所有行(但不着色)。
的\b都是字界碑以便它匹配如失败,但不是失败。它们不是必需的,因此如果您想匹配部分单词,请删除它们。
这是我昨天编写的 supercat 的示例包装脚本。它有效,但在编写它时,我发现 supercat 没有任何不区分大小写搜索的选项。IMO,这使得该程序的用处大大降低。但是,它确实大大简化了脚本,因为我不必编写“-i”选项:)
Package: supercat Description-en: program that colorizes text for terminals and HTML Supercat is a program that colorizes text based on matching regular expressions/strings/characters. Supercat supports html output as well as standard ASCII text. Unlike some text-colorizing programs that exist, Supercat does not require you to have to be a programmer to make colorization rules. Homepage: http://supercat.nosredna.net/
这是一个用于为正则表达式模式着色的通用脚本(可能需要一些修饰):
#! /bin/bash
color_to_num () {
case $1 in
black) echo 0;;
red) echo 1;;
green) echo 2;;
yellow) echo 3;;
blue) echo 4;;
purple) echo 5;;
cyan) echo 6;;
white) echo 7;;
*) echo 0;;
esac
}
# default values for foreground and background colors
bg=
fg=
bold="$(tput bold)"
italics=""
boundary=""
while getopts f:b:sli option; do
case "$option" in
f) fg="$OPTARG";;
b) bg="$OPTARG";;
s) bold="";;
l) boundary=".*";;
i) italics="$(tput sitm)";;
esac
done
shift $(($OPTIND - 1))
pattern="$*"
if [ -n "$fg" ]; then
fg=$(tput setaf $(color_to_num $fg))
fi
if [ -n "$bg" ]; then
bg=$(tput setab $(color_to_num $bg))
fi
if [ -z "$fg$bg" ]; then
fg=$(tput smso)
fi
sed "s/${boundary}${pattern}${boundary}/${bold}${italics}${fg}${bg}&$(tput sgr0)/g"
Run Code Online (Sandbox Code Playgroud)
命名hilite.sh并以这种方式使用它:
$ ./BIN_PROGRAM | hilite.sh -f green PASS | hilite.sh -f red FAIL
$ # Here is an example one liner
$ echo -e "line 1: PASS\nline 2: FAIL" | hilite.sh -f green PASS | hilite.sh -f red FAIL
Run Code Online (Sandbox Code Playgroud)