在 bash 中为备用输出行着色的简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1831527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:27:17  来源:igfitidea点击:

Simple way to colour alternate output lines in bash

bashshellcommand-linecolors

提问by naught101

I have need to grep an entire directory for a string, and I get about 50 results. I would like to colour each second line, either text colour or background colour. Best would be a script that I can pipe the output of any command to, and so that it spits out the same (albeit coloured) output.

我需要为一个字符串 grep 整个目录,我得到大约 50 个结果。我想为每一行着色,文本颜色或背景颜色。最好是一个脚本,我可以将任何命令的输出通过管道传输到它,这样它就可以输出相同的(尽管是彩色的)输出。

回答by Kimvais

Not very pretty but does the trick:

不是很漂亮,但有诀窍:

(save this to foo.bashand do grep whatever wherever | ./foo.bash)

(保存foo.bash并执行grep whatever wherever | ./foo.bash

#!/bin/bash
while read line
do
  echo -e "\e[1;31m$line"
  read line
  echo -e "\e[1;32m$line"
done
echo -en "\e[0m"

Here you can find the list of color codes in bash.

在这里您可以找到bash 中的颜色代码列表

回答by JasonSmith

Perl is installed on many systems. You could have it alternate for you:

Perl 安装在许多系统上。你可以让它为你替代:

grep -r whatever somedir/ | perl -pe '$_ = "3[1;29m$_3[0m" if($. % 2)'

In Perl $.can be substituted with $INPUT_LINE_NUMBERif you prefer readability.

如果您更喜欢可读性,在 Perl$.中可以替换为$INPUT_LINE_NUMBER

回答by Kimvais

and here is the same in python;

这在python中也是一样的;

import sys
for line_number,line in enumerate(sys.stdin.readlines()):
    print '%s[1;3%dm%s%s[0m' % (chr(27),(line_number % 2+1),line,chr(27)),

回答by pixelbeat

This is to delineate wrapped lines I presume? This shell script uses a background color from the 256 colorpalette, so as not to interfere with other highlighting that grep --color might do.

这是为了描绘我认为的包裹线?此 shell 脚本使用256 色调色板中的背景颜色,以免干扰 grep --color 可能执行的其他突出显示。

#!/bin/sh
c=0
while read line; do
  [ $(($c%2)) -eq 1 ] && printf "3[48;5;60m"
  printf "%s3[0m\n" "$line"
  c=$(($c+1))
done

This has the caveat that backslashes etc. within the line will be mangled, so treat this as pseudo code for reimplementation

这有一个警告,即行内的反斜杠等将被破坏,因此将其视为重新实现的伪代码