
vim ~/.bashrc
alias grep='grep --color'
2退出保存
source ~/.bashrc
只有执行grep命令搜索的时候,关键字就会有颜色了
也可以临时查询的时候,添加颜色
ps -ef | grep --color "timer"
对于Linux管理员来说,grep是日常最常用的命令,可以把匹配的字符输出,同样可以输出颜色。# grep --color 'test' /var/log/maillog
无聊练功:用perl 实现grep --color
# vi colorgrep
#!/usr/bin/perl
use Term::ANSIColor
my $test
if (@ARGV != 2){
die "Please use (colorgrep 'some key word' filename)\n"
}
$test = shift @ARGV
while(<>){
if(/$test/i){
print "$`"
print color "bold red"
print "$&"
print color 'reset'
print "$'"
}
}
这里调用了Term::ANSIColor 函数 color 有以下的参数:
clear, reset, dark, bold, underline, underscore, blink, reverse, concealed, black, red, green, yellow, blue, magenta, cyan, white, on_black, on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, and on_white
还有以下的简化使用方法
2) use Term::ANSIColor qw(:constants)
如果使用这种方法,可以直接把颜色属性放在要输出的问题前面,从而简化输出步骤。这些颜色属性有:
CLEAR, RESET, BOLD, DARK, UNDERLINE, UNDERSCORE, BLINK, REVERSE, CONCEALED, BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, ON_BLACK, ON_RED, ON_GREEN, ON_YELLOW, ON_BLUE, ON_MAGENTA, ON_CYAN, and ON_WHITE
等。
例如:
print BOLD BLUE ON_WHITE “Text”, RESET, “\n”
如果你打印完之后想清除掉字符串的格式,一定要记得在最后加上一个RESET的属性值。
例如:
use Term::ANSIColor qw(:constants)
print BOLD, BLUE, “This text is in bold blue.\n”, RESET
3) $Term::ANSIColor::AUTORESET = 1
对于2)的方法,如果你不想在每条打印语句后面加上RESET的话,你可以直接把$Term::ANSIColor::AUTORESET的值设为true。这样每次打印完字符,只要你的属性值之间没有逗号,系统将自动帮你清除掉颜色属性。
看一个完整的例子:
use Term::ANSIColor qw(:constants)
$Term::ANSIColor::AUTORESET = 1
print BOLD BLUE “This text is in bold blue.\n”
print “This text is normal.\n”
这三种方法,使用起来各有千秋,可根据要打印的复杂程度选用。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)