0

I need to create a script, that will read a word as an input and provide the output as shuffled letters of the word.

Eg: Input word as "Azharudeen" and output should be as "zAhauredne"

1

You could do this with a short Python script specified on the command line:

$ python -c "import random,sys; chars=list(sys.argv[1]); random.shuffle(chars); print(''.join(chars))" Azharudeen
neuAazrhed

  • For executing the above command we need to install any packages related to python? – azardin May 15 at 0:21
  • @azardin No, Python ships with Ubuntu. This should work in all versions, but note that python command is python 2.7 on versions prior to 18.04, and on Ubuntu 18.04 this should invoke python 3 – Sergiy Kolodyazhnyy May 15 at 4:24
1

Not the most elegant, but this works:

$ echo `echo "Azharudee" | sed -e 's/./&\n/g' | shuf` | sed -e 's/ //g'
Auerdzhae

Edit (for explanation):

echo "Azharudee"

puts that word into standard output, which is piped into

sed -e 's/./&\n/g'

which places each character onto its own line, by replacing each character by itself followed by a newline character, and pipes it into

shuf

which randomly shuffles the lines it is given and puts them on standard output.

Meanwhile this outer layer wraps all the above (as "...") in

echo `...` | sed -e 's/ //g'

The "echo" causes the multiple lines produced by the first set of commands to be combined into a single line, and the "sed" replaces all the spaces with nothing.

Note that it might have been visually better had I used $(echo ... shuf) rather than enclosing it in grave accents, which have the same effect but are harder to see.

  • Thanks for the command its working ! – azardin May 15 at 0:22
  • could you explain the below flag/commands which is used in the script line? sed -e 's/./&\n/g' | shuf` | sed -e 's/ //g' – azardin May 15 at 0:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.