I try to use bash to strip ANSI color escape sequences from a string without success. I tried already some regex-based code.
#!/bin/bash
Blue='\033[0;34m' # Blue
Clear='\033[0m' # Text Reset
removeColors (){
local uncolored_string=''
local import_row='import re; \n'
local regex_='(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]'
local func_def_row='def escape_ansi(line): \n'
local ansi_escape_row="ansi_escape=re.compile(r\'$regex_\') \n"
local return_row="return ansi_escape.sub('', line) \n"
local print_row="print escape_ansi(line = '$1')"
local code="$import_row$func_def_row$ansi_escape_row$return_row$print_row"
echo $(python -c $code)
}
str="Press ${Blue}any key${Clear} to continue..."
echo -e "$str"
removeColors "$str"
I still receive the code below.
File "<string>", line 1
import
^
SyntaxError: invalid syntax
Can you help me?
Update:
I found the python library strip-ansi.
removeColors (){
local uncolored_string=''
local ansi_snippet="$1"
echo "$(python3 -c "from strip_ansi import strip_ansi; print(strip_ansi(\"$ansi_snippet\"))")"
}
However, even after installing it, I receive the error below:
Traceback (most recent call last):
File "<string>", line 1, in <module>
ModuleNotFoundError: No module named 'strip_ansi'