Bash - scrambling characters contained in a string

So I have this function with the following output:

    AGsg4SKKs74s62#

      

I need to find a way to scramble characters without deleting anything .. so all characters should be present after I scramble them.

I can only use bash utilities including awk and sed.

+3


source to share


3 answers


echo 'AGsg4SKKs74s62#' | sed 's/./&\n/g' | shuf | tr -d "\n"

      

Output (for example):



S7s64#2gKAGsKs4

      

+7


source


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


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







All Articles