1

Normally I use the ${parameter/pattern/string} construct in bash to replace characters.

For example, ${i//(/_} replaces all ( characters with _ in $i.  For illustration:

find . -depth -type d -name '*(*' -execdir bash -c 'for i; do mv "$i" "${i//(/_}"; done' _ {} +

I cannot get it to work with ~.  ${i//~/_} yields the value of $i, unchanged, even if it contains tilde(s).

It's weird – it works with every single other symbol I use except a question mark. Any ideas with the tilde?

JandP
  • 31

1 Answers1

3

bash(1) doesn’t clearly document the fact that, when you do

${parameter/pattern/string}
the pattern and string are subject to all the expansions that apply to plain (unquoted) words on the command line.  Consider this example:
$ balance=credit

$ fire=red

$ sky=blue

$ echo "${balance/$fire/$sky}" cblueit

Your problem, of course, is that ~ gets expanded to your home directory:

$ i=foo/home/JandPbar

$ echo "${i/~/_}" foo_bar

So, as suggested in the comment, you need to quote/escape the ~, with "${i/'~'/_}" or "${i/\~/_}".