如何从标准输出和管道中去除颜色代码到文件和标准输出

iam*_*ton 16 bash shell-script bash-script

我有一个程序,使用printf一些tput在它混合,我想管道输出到stdout和文件。我更喜欢使用,sed因为我不希望对我的脚本有任何不必要的依赖。这是我到目前为止所得到的。

printf "\n$(tput setaf 6)| $(tput sgr0)$(tput setaf 7)Sourcing files...\033[m\n" | tee install.log

唯一的问题是我的日志文件正在获取所有颜色输出...

^[[36m| ^[(B^[[m^[[37mSourcing files...^[[m

我希望它只是有 | Sourcing files...

小智 13

根据从 output 中删除颜色,您的命令应该是:

printf "\n$(tput setaf 6)| $(tput sgr0)$(tput setaf 7)Sourcing files...\033[m\n" |\
sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g" |tee install.log
w/o "-r"
sed "s/\x1B\[\([0-9]\{1,2\}\(;[0-9]\{1,2\}\)\?\)\?[mGK]//g"
Run Code Online (Sandbox Code Playgroud)

为方便起见,您还可以在 /etc/profile

alias stripcolors='sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g"'
w/o '-r'
alias stripcolors='sed "s/\x1B\[\([0-9]\{1,2\}\(;[0-9]\{1,2\}\)\?\)\?[mGK]//g"'
Run Code Online (Sandbox Code Playgroud)

[编辑]

使用给定的输出,您可以自己检查:

#!/usr/bin/perl

while ($line=<DATA>) {
    $line =~ s/^[0-9a-f]+: //;
    while ($line =~ s/([0-9a-f]{2})(?=[0-9a-f]{2}| )//) {
      print chr(hex($1));
    }
}
__DATA__
0000000: 1b5b 316d 1b5b 3333 6de2 9aa0 2020 5761 .[1m.[33m... Wa
0000010: 726e 696e 673a 201b 2842 1b5b 6d4e 6f20 rning: .(B.[mNo
0000020: 2f55 7365 7273 2f61 7077 2f2e 6261 7368 /Users/apw/.bash
0000030: 2066 6f75 6e64 2e21 0a found.!.
Run Code Online (Sandbox Code Playgroud)

输出:

$ perl checkerbunny|xxd
0000000: 1b5b 316d 1b5b 3333 6de2 9aa0 2020 5761  .[1m.[33m...  Wa
0000010: 726e 696e 673a 201b 2842 1b5b 6d4e 6f20  rning: .(B.[mNo 
0000020: 2f55 7365 7273 2f61 7077 2f2e 6261 7368  /Users/apw/.bash
0000030: 2066 6f75 6e64 2e21 0a                    found.!.

$ perl checkerbunny|stripcolors|xxd
0000000: e29a a020 2057 6172 6e69 6e67 3a20 1b28  ...  Warning: .(
0000010: 424e 6f20 2f55 7365 7273 2f61 7077 2f2e  BNo /Users/apw/.
0000020: 6261 7368 2066 6f75 6e64 2e21 0a         bash found.!.
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,这_不_在 OS X 上工作。 (3认同)