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'
python -c import, so perhaps the first issue is the unquoted shell variable$code? – steeldriver Feb 07 '22 at 00:12\nis not taken literal here. You could use$'...'. However, you have also increment errors foransi_escape_rowandreturn_row. And probably other issues as well. Better not to mix shell and python code. – pLumo Feb 07 '22 at 07:56pythonversion doespip -Vreturn. If 2.x, you can trypip3 install strip_ansiorpython3 -m pip install strip_ansi– pLumo Feb 07 '22 at 15:14ansi2txt? – pLumo Feb 07 '22 at 15:19strip-ansi, but usestrip_ansiwith underscore. Documentation has two different versions of their installation instructions ?! – pLumo Feb 07 '22 at 15:29echo, it does not evaluate to ansi codes. Useecho -eorprintfand it works just fine. – pLumo Feb 07 '22 at 15:40