'Regex find and replace special chars with underscore

I apologize because I know this has been asked so many times. Yet, I cannot find an answer that works for me! It seems most answers seem framed in a particular language like Java or php. I'm trying to make this work in "pure" regex format at the termimal (mac) line. This bit of code works but I'd like to find special chars and replace with underscores. As it is right now, the regex replaces with nothing. Any idea how I can specify the replace value?

find . -type f|while read f;do b=${f##*/};mv "$f" "${f%/*}/${b//[^[:alnum:]_.]}";done 


Solution 1:[1]

You can specify the replacement after another /:

"${f%/*}/${b//[^[:alnum:]_.]/_}"
#                           ??

Here, ${b//[^[:alnum:]_.]/_} means that any single char other than a letter, digit, underscore and dot will be replaced with a _ char.

If you need to replace chunks of one or more special chars with a single underscore use

shopt -s extglob
"${f%/*}/${b//+([^[:alnum:]_.])/_}"
shopt -u extglob

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1