我有一些脚本,产生输出的颜色,我需要删除ANSI代码。

#!/bin/bash

exec > >(tee log)   # redirect the output to a file but keep it on stdout
exec 2>&1

./somescript

输出为(在日志文件中):

java (pid  12321) is running...@[60G[@[0;32m  OK  @[0;39m]

我不知道如何在这里放置ESC字符,所以我把@放在它的位置。

我把剧本改成:

#!/bin/bash

exec > >(tee log)   # redirect the output to a file but keep it on stdout
exec 2>&1

./somescript | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g"

但是现在它给了我(在日志文件中):

java (pid  12321) is running...@[60G[  OK  ]

我怎么也可以删除这个'@[60G?

也许有一种方法可以完全禁用整个脚本的着色?


当前回答

不确定./somescript中有什么,但如果转义序列没有硬编码,您可以设置终端类型来避免它们

TERM=dumb ./somescript 

例如,如果你尝试

TERM=dumb tput sgr0 | xxd

您将看到它在while时没有输出

tput sgr0 | xxd
00000000: 1b28 421b 5b6d                           .(B.[m

Does(对于xterm-256color)。

其他回答

下面的正则表达式将错过一些ANSI转义码序列,以及3位颜色。regex101.com的示例和修复。

用这个代替:

./somescript | sed -r 's/\x1B\[(;?[0-9]{1,3})+[mGK]//g'

我也有问题,有时,SI字符出现。

例如,输入echo "$(tput setaf 1)foo$(tput sgr0) bar"

这里有一种方法也可以剥离SI字符(shift in) (0x0f)

./somescript | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g" | sed "s/\x0f//g"

在纯Bash中更简单的函数从文本流中过滤出常见的ANSI代码:

# Strips common ANSI codes from a text stream

shopt -s extglob # Enable Bash Extended Globbing expressions
ansi_filter() {
  local line
  local IFS=
  while read -r line || [[ "$line" ]]; do
    printf '%s\n' "${line//$'\e'[\[(]*([0-9;])[@-n]/}"
  done
}

See:

扩展Globbing gnu.org: Bash参数扩展

我在Debian的有色日志包中遇到了ansi2txt工具。该工具删除来自STDIN的ANSI控制代码。

使用的例子:

./somescript | ansi2txt

源代码http://github.com/kilobyte/colorized-logs

@jeff-bowman的解决方案帮助我摆脱了一些颜色代码。 我在正则表达式中添加了另一小部分,以便删除更多:

sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g" # Original. Removed Red ([31;40m[1m[error][0m)
sed -r "s/\x1B\[([0-9];)?([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g" # With an addition, removed yellow and green ([1;33;40m[1m[warning][0m and [1;32;40m[1m[ok][0m)
                ^^^^^^^^^
                remove Yellow and Green (and maybe more colors)

我也遇到过类似的问题。我发现的所有解决方案都适用于颜色代码,但没有删除“$(tput sgr0)”添加的字符(重置属性)。

以davemyron注释中的解决方案为例,在下面的例子中,结果字符串的长度是9,而不是6:

#!/usr/bin/env bash

string="$(tput setaf 9)foobar$(tput sgr0)"
string_sed="$( sed -r "s/\x1B\[[0-9;]*[JKmsu]//g" <<< "${string}" )"
echo ${#string_sed}

为了正常工作,regex必须扩展以匹配由sgr0 ("\E(B"))添加的序列:

string_sed="$( sed -r "s/\x1B(\[[0-9;]*[JKmsu]|\(B)//g" <<< "${string}" )"