Search code examples
regexbashsedglobtr

Obscure string in bash script


I am trying to do the following:

obscure ( ) {
    local txt="$1"
    echo "$txt" | tr '[:alnum:]' '*'
}

So that if I do:

obscure 'mysecretstring'

I get:

**************

What matcher can I use for tr, instead of [:alnum:] to mean 'any character'?

Is there a better way to implement obscure? Another option that comes to mind is sed.


Solution

  • You can use pure BASH:

    obscure() {
       local txt="$1"
       echo "${txt//?/*}"
    }
    

    "${txt//?/*}" will replace each character in $txt by *

    Test it:

    obscure 'mysecretstring3123213213'
    ************************
    
    obscure mysecretstring
    **************
    
    obscure '!@#$%^&*()_+=-'
    **************
    
    obscure '中文版'
    ***