Bash string replace multiple chars with one

You need something more powerful than traditional shell wildcards. In bash, set the extglob option, which gives you access to regular expressions in glob patterns through an unusual syntax inherited from ksh.

shopt -s extglob
sanitized=${raw//+([^A-Za-z0-9])/-}

tr is a good tool for this job

new=$( printf "%s" "$t" | tr -cs 'a-zA-Z0-9' '-' )
new=${new#-}; new=${new%-}

If you want to stay with pure bash, you'll have to settle for the two-pass solution. Bash string substitutions use globs, as in pathname expansion, and not regular expressions. The only special characters in globs are *, ?, and [], whose rough equivalents in regular expressions are .*, ., and []. Take a look at the Wooledge wiki and the bash(1) man page sections on Parameter Expansion and Pathname Expansion for more info.

Just as a comment, a two-pass expansion in pure bash is still likely to be faster than trying to do the same thing by invoking an external program, so I wouldn't worry about it too much.

Tags:

String

Shell

Bash