How to strip ANSI escape sequences from a variable?

后端 未结 2 1700
误落风尘
误落风尘 2020-12-19 20:35

Weird question. When I set a variable in Bash to display as a certain color, I don\'t know how to reset it. Here is an example:

First define the color code:

相关标签:
2条回答
  • 2020-12-19 20:59

    Here is a pure Bash solution:

    ERROR="${ERROR//$'\e'\[*([0-9;])m/}"
    

    Make it a function:

    # Strips ANSI codes from text
    # 1: The text
    # >: The ANSI stripped text
    function strip_ansi() {
      shopt -s extglob # function uses extended globbing
      printf %s "${1//$'\e'\[*([0-9;])m/}"
    }
    

    See:

    • Bash Shell Parameter Expansion
    • Bash Pattern-Matching
    0 讨论(0)
  • 2020-12-19 21:05

    You almost had it. Try this instead:

    ERROR=$(echo "$ERROR" | sed 's%\o033\[33m%%g')
    

    Note, however, that the use of the \oNNN escape sequence in sed is a GNU extension, and thus not POSIX compliant. If that is an issue, you should be able to do something more like:

    ERROR=$(echo "$ERROR" | sed 's%'$(echo -en "\033")'\[33m%%g')
    

    Obviously, this will only work for this one specific color (yellow), and a regex to remove any escape sequence (such as other colors, background colors, cursor positioning, etc) would be somewhat more complicated.

    Also note that the -r is not required, since nothing here is using the extended regular expression syntax. I'm guessing you already know that, and that you just included the -r out of habit, but I mention it anyway just for the sake of clarity.

    0 讨论(0)
提交回复
热议问题