Pipable命令以彩色打印?
我对bash脚本有点新,我想知道是否有一个程序或内置命令管道将以指定的颜色打印? 或者是否有回声参数?
像我能做的那样:
echo Hi | commandhere -arguement blue
它会以蓝色打印“Hi”吗?
我不知道彩色打印本身的任何实用程序,但你可以使用这样的shell函数轻松完成:
# colorize stdin according to parameter passed (GREEN, CYAN, BLUE, YELLOW) colorize(){ GREEN="\033[0;32m" CYAN="\033[0;36m" GRAY="\033[0;37m" BLUE="\033[0;34m" YELLOW="\033[0;33m" NORMAL="\033[m" color=\$${1:-NORMAL} # activate color passed as argument echo -ne "`eval echo ${color}`" # read stdin (pipe) and print from it: cat # Note: if instead of reading from the pipe, you wanted to print # the additional parameters of the function, you could do: # shift; echo $* # back to normal (no color) echo -ne "${NORMAL}" } echo hi | colorize GREEN
如果要查看其他颜色,请查看此列表 。 您可以从那里添加对任何颜色的支持,只需在此函数中使用正确的名称和值创建其他变量。
我创建了这个我在bash脚本中使用的函数。
#以指定颜色回显的function echoincolor(){ 案例1美元 “red”)tput setaf 1 ;; “green”)tput setaf 2 ;; “orange”)tput setaf 3 ;; “blue”)tput setaf 4 ;; “紫色”)tput setaf 5 ;; “青色”)tput setaf 6 ;; “灰色”| “灰色”)tput setaf 7 ;; “white”)tput setaf 8 ;; ESAC 回声“$ 2”; tput sgr0 }
然后我就像把它echoincolor green "This text is in green!"
或者 ,使用printf
#以指定颜色打印的function colorprintf(){ 案例1美元 “red”)tput setaf 1 ;; “green”)tput setaf 2 ;; “orange”)tput setaf 3 ;; “blue”)tput setaf 4 ;; “紫色”)tput setaf 5 ;; “青色”)tput setaf 6 ;; “灰色”| “灰色”)tput setaf 7 ;; “white”)tput setaf 8 ;; ESAC printf“$ 2”; tput sgr0 }
然后就像这个colorprintf green "This text is in green!"
调用它colorprintf green "This text is in green!"
注意 , echo
提供了一个尾随的新行,而printf
则没有。
我使用这个旧脚本,名称为hilite.pl,取自网络,已经与“未知作者”行!
#!/usr/bin/perl -w ### Usage: hilite ### Purpose: Will read text from standard input and perform specified highlighting ### command before displaying text to standard output. ### License: GNU GPL # unknown author $|=1; # don't buffer i/o $command = "$ARGV[0]"; $target = "$ARGV[1]"; $color = "\e[" . $command . "m"; $end = "\e[0m"; while() { s/($target)/$color$1$end/; print $_; }
然后我可以使用regexp / PCRE在管道,“hilite”日志输出或其他东西中使用它:
echo 'hello color world!!' | hilite.pl 34 "[Hh]el[^ ]*" | hilite.pl 43 .orld | hilite.pl 32 "\scolor\s"
这将以蓝色,绿色和黄色背景的世界绘制你好
您可以看到颜色列表(如果需要,可以将bash表达式扩展为{01..255}):
for i in {01..10} {30..49} {90..110} ; do echo $i | hilite.pl $i $i ; done
有一个比这些更优雅的答案:
sudo apt-get install grc
(也安装了grcat
)
现在执行:
echo "[SEVERE] Service is down" | grcat ~/conf.username
conf.myusername
包含的位置:
regexp=SEVERE colours=on_red count=more
(由于某种原因,我找不到“引号之间的所有东西”的正确的正则表达式)