例如,我想为locate命令的输出着色,以便它可以很容易地与其他终端文本区分开来.
它应该是这样的:
@H_403_4@locate -bir pdf | some_command_to_color_the_result着色不应仅限于locate命令:我需要一个通用解决方案,使用管道为文本着色,例如将其输入grep或cat的输出.
如果没有内置的Linux命令,那么任何关于如何创建一个Linux命令的提示都会受到赞赏.
解决方法
@H_403_4@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’)