Bash – How to use sed to replace text with special characters

bashscriptingsed

I currently have a script that generates random words to create passwords. I run this by selecting the script and letting it know how many words I want .e.g ./generate_passwords.sh 5. This creates five strong words.

This is the bit I am having trouble with. I want to pipe this into sed which should take the spaces between those words and replace them with random special characters. Is there a way to do this?

e.g ./generate_passwords.sh 5 | sed 's/ //g' (This removes all spaces and inserts nothing.)

This should be the desired outcome: word#word*word!

Best Answer

You can implement the following logic:

  • Define a string variables symbols with the symbols to pick from randomly
  • Loop as long as the string contains spaces
  • Use ((RANDOM % ${#symbols})) to pick a random index
  • Replace a space with the symbol at the randomly picked index

Like this:

s=$(./generate_passwords.sh 5)
symbols='#*!'
while [[ $s == *\ * ]]; do
    ((index = RANDOM % ${#symbols}))
    s=${s/ /${symbols:index:1}}
done
echo "$s"

I used parameter expansion (${s/.../...}) instead of sed. Since this is a native Bash feature, it will be much faster than repeatedly running a sed process.