How to strip ANSI escape sequences from a variable?

后端 未结 2 1708
误落风尘
误落风尘 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 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.

提交回复
热议问题