jlp jlp - 7 months ago 29
Bash Question

How to remove special characters from strings but keep underscores in shell script

I have a string that is something like "info_A!__B????????C_*". I wan to remove the special characters from it but keep underscores and letters. I tried with [:word:] (ASCII letters and _) character set, but it says "invalid character set". any idea how to handle this ? Thanks.

text="info_!_????????_*"
if [ -z `echo $text | tr -dc "[:word:]"` ]
......

Answer

Using bash parameter expansion:

$ var='info_A!__B????????C_*'

$ echo "${var//[^[:alnum:]_]/}"
info_A__BC_