通过滤色器传递命令

Geo*_*rge 13 colors bash terminal

Unix 中有这样的东西吗?

$ echo "this should show in red" | red
$ echo "this should show in green" | green
$ echo "this should show in blue" | blue
Run Code Online (Sandbox Code Playgroud)

在这里,我的意思不是要出现文字颜色代码文本(例如,粘贴到文件中)。我只是想让文本在终端中实际显示为该颜色。这可能吗?

Ste*_*itt 23

你会使用tput

tput setaf 1
echo This is red
tput sgr0
echo This is back to normal
Run Code Online (Sandbox Code Playgroud)

这可用于构建管道:

red() { tput setaf 1; cat; tput sgr0; }
echo This is red | red
Run Code Online (Sandbox Code Playgroud)

基本颜色分别为黑色(0)、红色(1)、绿色、黄色、蓝色、品红色、青色和白色(7)。您可以在terminfo(5)联机帮助页中找到所有详细信息。


ter*_*don 14

这是一个可以做到这一点的小脚本。将其另存为color您的目录中$PATH(例如,~/bin如果它在您的 中$PATH):

#!/usr/bin/env perl

use strict;
use warnings;
use Term::ANSIColor; 

my $color=shift;
while (<>) {
    print color("$color").$_.color("reset");
} 
Run Code Online (Sandbox Code Playgroud)

然后,通过脚本传递您的文本,.作为要匹配的模式并指定颜色:

运行脚本的终端屏幕截图

支持的颜色取决于终端的能力。有关详细信息,请参阅文件中的Term::ANSIColor包。


Sté*_*las 6

zsh

autoload colors; colors
for color (${(k)fg})
  eval "$color() {print -n \$fg[$color]; cat; print -n \$reset_color}"
Run Code Online (Sandbox Code Playgroud)

进而:

$ echo "while" | blue
while
Run Code Online (Sandbox Code Playgroud)