1

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!

2 Answers 2

1

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.

0

sed 's/ //g' removes all spaces and inserts nothing, as you write :)

sed 's/ /#/g' replaces all spaces to dies (#).

So, you need

 | sed 's/ /\#/'  | sed 's/ /*/'  | sed 's/ /!/' 
2
  • Thanks for the comment. Is there a way to make the special characters random?
    – Neil
    Sep 30, 2016 at 13:10
  • Sorry, I dont understand you question.
    – Smithson
    Sep 30, 2016 at 13:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .