简体   繁体   English

用不同的颜色给 output 上色

[英]Colorize output with different color

I need to colour output using ANSI color for example in blue then we cat a file.我需要使用 ANSI 颜色为 output 上色,例如蓝色,然后我们抓取一个文件。 But if we grep word error in file this words must be colored red但是如果我们在文件中出现 grep 字错误,这个字必须是红色的

I try to use grep --colour=always but it reset the coloring to default after word match我尝试使用 grep --colour=always 但它在单词匹配后将颜色重置为默认值

For example my console is blue text now, but if i use例如我的控制台现在是蓝色文本,但如果我使用

cat test.txt | grep -E --color=auto '.*line.*|$'
this is line 2 <<<---this line is red
just doing something <<<- this line is black

Console安慰

And i need console back to blue color我需要控制台回到蓝色

I expect console back to blue color我希望控制台回到蓝色

You can mess with the GREP_COLORS environment variable before running grep .在运行grep之前,您可以弄乱GREP_COLORS环境变量。

GREP_COLORS='sl=36:cx=36' grep -E '.*line.*|$' filename

will color the 'selected line' and 'context line' in the escape color code you set it to (36 being cyan, in this example)将为您设置的转义颜色代码中的“选定行”和“上下文行”着色(在此示例中,36 为青色)

I will happily give credit to the answer here to use for more reference: https://unix.stackexchange.com/questions/705097/default-value-for-the-grep-colors-environment-variable我很乐意将这里的答案归功于更多参考: https://unix.stackexchange.com/questions/705097/default-value-for-the-grep-colors-environment-variable

If you still need the terminal colors to be cyan (or whatever color you originally chose) after the grep runs, I'd try just echoing the escape sequence after your call to grep.如果在 grep 运行后您仍然需要终端 colors 为青色(或您最初选择的任何颜色),我会尝试在您调用 grep 后回显转义序列。

Side note: run your script through shellcheck, cat is redundant with grep. Instead of旁注:通过 shellcheck 运行脚本,cat 与 grep 是多余的。而不是
cat filename | grep mystring cat filename | grep mystring just use grep mystring filename cat filename | grep mystring只需使用grep mystring filename

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM