Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash- scramble characters contained in a string

So I have this function with the following output:

    AGsg4SKKs74s62#

I need to find a way to scramble the characters without deleting anything..aka all characters must be present after I scramble them.

I can only bash utilities including awk and sed.

like image 844
Bruce Strafford Avatar asked Oct 12 '14 14:10

Bruce Strafford


People also ask

What does [- Z $1 mean in Bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script.

How do you check if a string contains a substring in Bash?

To check if a string contains a substring in Bash, use comparison operator == with the substring surrounded by * wildcards.

How do you check if a character is present in a string in shell script?

The grep command can also be used to find strings in another string. In the following example, we are passing the string $STR as an input to grep and checking if the string $SUB is found within the input string. The command will return true or false as appropriate.

How do you slice a string in Bash?

Using the cut Command You can also use the -d and -f flags to extract a string by specifying characters to split on. The -d flag lets you specify the delimiter to split on while -f lets you choose which substring of the split to choose.


2 Answers

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

Output (e.g.):

S7s64#2gKAGsKs4
like image 70
Cyrus Avatar answered Sep 22 '22 19:09

Cyrus


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 it works:

$ scramble 'AGsg4SKKs74s62#'
$ echo "$scramble_ret"
G4s6s#2As74SgKK

Looks all right.

like image 37
gniourf_gniourf Avatar answered Sep 24 '22 19:09

gniourf_gniourf