Bash - scrambling characters contained in a string
3 answers
Here's a pure Bash function that does the job:
scramble() {
# $1: string to scramble
# return in variable scramble_ret
local a=$1 i
scramble_ret=
while((${#a})); do
((i=RANDOM%${#a}))
scramble_ret+=${a:i:1}
a=${a::i}${a:i+1}
done
}
See if this works:
$ scramble 'AGsg4SKKs74s62#'
$ echo "$scramble_ret"
G4s6s#2As74SgKK
Looks good.
+4
source to share
I know you didn't mention Perl, but you can do it like this:
perl -MList::Util=shuffle -F'' -lane 'print shuffle @F' <<<"AGsg4SKKs74s62#"
-a
turns on auto split mode and -F''
sets the field separator to an empty string, so each character goes to a separate element in the array. The array is shuffled using a function provided by the main module List::Util
.
+3
source to share