从字符串中去除前导和尾随 ansi/tput 代码

Strip leading AND trailing ansi/tput codes from string

此处的应用是 "sanitizing" 字符串,用于包含在日志文件中。为了争论,我们假设 1) 在运行时给字符串着色是正确的;和 2) 我需要在屏幕上显示前导和尾随空格,但从日志中删除多余的空格。

这里的具体应用是发球到日志文件中。不是所有的行都会被着色,也不是所有的行都会有 leading/trailing 个空格。

鉴于此,我想

  1. 删除设置颜色重置的所有代码。稍后就会明白其中的原因
  2. 删除前导和尾随空格

当您(在任何地方)搜索如何去除 bash 中的颜色代码时,您可以找到 many different ways 来完成它。然而,到目前为止我发现似乎没有人解决尾随重置问题; $(tput sgr0)。在我看到的示例中,这是无关紧要的,但是我对删除 leading/trailing 空格的额外要求使 it/makes 复杂化,这是一项要求。

这是我的示例脚本,它演示了这个问题:

#!/bin/bash

# Create a string with color, leading spaces, trailing spaces, and a reset
REPLY="$(tput setaf 2)       This is green        $(tput sgr0)"
echo "Colored output:  $REPLY"
# Remove initial color code
REPLY="$(echo "$REPLY" | sed 's,\x1B\[[0-9;]*[a-zA-Z],,g')"
echo "De-colorized output:  $REPLY"
# Remove leading and trailing spaces if present
REPLY="$(printf "%s" "${REPLY#"${REPLY%%[![:space:]]*}"}" | sed -n -e 'l')"
echo "Leading spaces removed:  $REPLY"
REPLY="$(printf "%s" "${REPLY%"${REPLY##*[![:space:]]}"}" | sed -n -e 'l')"
echo "Trailing spaces removed:  $REPLY"

输出是(不知道如何给文本着色,假设第一行是绿色,后面几行不是):

我愿意看到我的错误,但在尝试不同的东西大约三个小时后,我很确定我的 google-fu 失败了。

感谢您的帮助。

这对我有用:

$ REPLY="$(tput setaf 2)       This is green        $(tput sgr0)"
$ echo -n $REPLY | od -vAn -tcx1
 033   [   3   2   m                               T   h   i   s
  1b  5b  33  32  6d  20  20  20  20  20  20  20  54  68  69  73
       i   s       g   r   e   e   n                            
  20  69  73  20  67  72  65  65  6e  20  20  20  20  20  20  20
     033   [   m 017
  20  1b  5b  6d  0f
$ REPLY=$(echo $REPLY | sed -r 's,\x1B[\[\(][0-9;]*[a-zA-Z]\s*(.*)\x1B[\[\(].*,,g' | sed 's/\s*$//')
$ echo -n $REPLY | od -vAn -tcx1
   T   h   i   s       i   s       g   r   e   e   n
  54  68  69  73  20  69  73  20  67  72  65  65  6e

显然 sed does not support 非贪婪正则表达式,这将消除第二个正则表达式。

编辑: 这个应该适用于您的输入:

$ REPLY="$(tput setaf 2)       This is green        "$'\x1B'"(B$(tput sgr0)"
$ echo -n $REPLY | od -vAn -tcx1
 033   [   3   2   m                               T   h   i   s
  1b  5b  33  32  6d  20  20  20  20  20  20  20  54  68  69  73
       i   s       g   r   e   e   n                            
  20  69  73  20  67  72  65  65  6e  20  20  20  20  20  20  20
     033   (   B 033   [   m 017
  20  1b  28  42  1b  5b  6d  0f
$ REPLY=$(echo "$REPLY" | sed -r -e 's,\x1B[\[\(][0-9;]*[a-zA-Z]\s*([^\x1B]+)\s+\x1B.*,,g' -e 's,\s*$,,')
$ echo -n $REPLY | od -vAn -tcx1
   T   h   i   s       i   s       g   r   e   e   n
  54  68  69  73  20  69  73  20  67  72  65  65  6e

与 bash 替换相比,我发现 sed 不那么神秘(或者像正则表达式一样不那么神秘)。但这就是我:)

I am willing to see the error of my ways, …

主要错误只是 sed 命令只删除了 Esc[... 控制序列,而不是Esc(B 序列也是 sgr0 的一部分。如果你改变它就有效它

… | sed 's,\x1B[[(][0-9;]*[a-zA-Z],,g'

第二个错误是 sed -n -e 'l' 命令在行尾添加了文字 $ 符号,因此之前的尾随空格不再尾随,因此不会被删除。