例如,我想为locate
命令的输出着色,以便与其他终端文本轻松区分.
它应该是这样的:
locate -bir pdf | some_command_to_color_the_result
着色不应仅限于locate
命令:我需要一个通用的解决方案,使用管道为文本着色,例如将其输出为grep
或cat
.
如果没有内置的Linux命令,那么有关如何创建一个Linux命令的任何提示都会受到赞赏.
norm="$(printf '\033[0m')" #returns to "normal" bold="$(printf '\033[0;1m')" #set bold red="$(printf '\033[0;31m')" #set red boldred="$(printf '\033[0;1;31m')" #set bold, and set red. somecommand | sed -e "s/someregexp/${boldred}&${norm}/g" # will color any occurence of someregexp in Bold red printf "%s" "$red" ; locate something ; printf "%s" "$norm" # will color output of locate something in red #I (ab)use printf "%s" "something", as it's more portable than echo,and easy to modify
还有很多其他的方法(创建一个函数/脚本,可以上色一个正则表达式,例如,然后: somecommand | colorize -c green 'foo.*bar' 'other'
)
您可以使用转义序列将任何输出的字体颜色更改为bash shell.以下是您需要的一些颜色代码:
BLACK="\033[30m" RED="\033[31m" GREEN="\033[32m" YELLOW="\033[33m" BLUE="\033[34m" PINK="\033[35m" CYAN="\033[36m" WHITE="\033[37m" NORMAL="\033[0;39m"
一旦定义了这些,就可以在普通的echo命令中使用它们.例如:
echo -e $GREEN this text is green $NORMAL and this is normal
请注意,-e并不总是必需的,但在某些操作系统(包括osx)上需要启用转义序列.
根据这些定义,您可以构建脚本和管道,以便为其他命令的输出着色.这是我用来为以下输出着色的完整示例svn up
:
#!/bin/bash BLACK="\033[30m" RED="\033[31m" GREEN="\033[32m" YELLOW="\033[33m" BLUE="\033[34m" PINK="\033[35m" CYAN="\033[36m" WHITE="\033[37m" NORMAL="\033[0;39m" TMPFILE=.cvsup.tmp svn up > $TMPFILE svn status >> $TMPFILE printf $YELLOW grep -e ^"\? " -e ^"I " $TMPFILE printf $GREEN grep -e ^"R " -e ^"U " -e ^"G " $TMPFILE printf $BLUE grep -e ^"M " -e ^"E " $TMPFILE printf $RED grep -e ^"C " -e ^"! " -e ^"X " -e ^"~ " $TMPFILE printf $PINK grep ^"R " $TMPFILE printf $PINK grep ^"D " $TMPFILE printf $CYAN grep ^"A " $TMPFILE printf $NORMAL rm $TMPFILE
你也可以看看tput
.