根据外壳的正则表达式彩色高亮输出 [英] Colour highlighting output based on regex in shell

查看:117
本文介绍了根据外壳的正则表达式彩色高亮输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如果我能颜色来突出显示符合某些字符串一个shell命令的输出。

I'd like to know if I can colour highlight the output of a shell command that matches certain strings.

例如,如果我跑myCommand,与下面的输出:

For example, if I run myCommand, with the output below:

> myCommand
DEBUG foo bar
INFO bla bla
ERROR yak yak

我想所有线路匹配^ ERROR \\ S *被红色突出显示。

I'd like all lines matching ^ERROR\s.* to be highlighted red.

同样,我想相同的高亮被应用到grep的输出,少等...

Similarly, I'd like the same highlighting to be applied to the output of grep, less etc...

编辑:我也许应该提到,理想情况下,我想在全球范围内启用此功能通过在我的.bashrc一个'个人资料'选项

I probably should mention that ideally I'd like to enable this feature globally via a 'profile' option in my .bashrc.

推荐答案

如果你想在全球范围内实现这一点,你需要一个终端功能,而不是一个过程,你管的输出入,因为管道会破坏一些命令(两个问题是输出和错误会出现乱序和缓冲,而某些命令只是表现不同输出到终端时)。

If you want to enable this globally, you'll want a terminal feature, not a process that you pipe output into, because a pipe would be disruptive to some command (two problems are that stdout and stderr would appear out-of-order and buffered, and that some commands just behave differently when outputting to a terminal).

我不知道这个功能的任何传统的终端。它很容易在Emacs完成的,在缓冲区:配置字体锁定关键字长期模式

I don't know of any "conventional" terminal with this feature. It's easily done in Emacs, in a term buffer: configure font-lock-keywords for term-mode.

然而,你应该仔细考虑你是否真的需要该功能的所有时间。如果什么命令都有自己的颜色(例如的grep --color LS --color )?也许这将更好地定义一个简短的别名到<一个href=\"http://stackoverflow.com/questions/4267400/colour-highlighting-output-based-on-regex-in-shell/4269167#4269167\">colorizer命令并运行 myCommand 2 - ;&放大器; 1 | C当你想着色 myCommand 输出。你也可以<一href=\"http://stackoverflow.com/questions/4267400/colour-highlighting-output-based-on-regex-in-shell/4269864#4269864\">alias一些具体的始终着色指令的。

However, you should think carefully whether you really want that feature all the time. What if the command has its own colors (e.g. grep --color, ls --color)? Maybe it would be better to define a short alias to a colorizer command and run myCommand 2>&1|c when you want to colorize myCommand's output. You could also alias some specific always-colorize commands.

注意管道的返回状态是它的最后的命令,因此,如果您运行 myCommand | ç,您将获得的ç的状态,而不是 myCommand 。下面是避免了这个问题,你可以为下w myCommand一个bash包装

Note that the return status of a pipeline is its last command, so if you run myCommand | c, you'll get the status of c, not myCommand. Here's a bash wrapper that avoids this problem, which you can use as w myCommand:

w () {
  "$@" | c
  return $PIPESTATUS[0]
}

这篇关于根据外壳的正则表达式彩色高亮输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆