Skip to content

Instantly share code, notes, and snippets.

@abiriadev
Last active May 9, 2023 18:03
Show Gist options
  • Save abiriadev/f2882299bb5ab50af642bc2c26fdc78f to your computer and use it in GitHub Desktop.
Save abiriadev/f2882299bb5ab50af642bc2c26fdc78f to your computer and use it in GitHub Desktop.
Roll n characters from given string

Usage

Randomly pick N characters from a given string(or standard input), just like rolling a dice repeatedly, then concatenate them into a single string.

Note

Please note that:

  1. It might containe repeated items. If you want to just shuffle them, try removing -r option from shuf command.

  2. It will treat unicode character as one item. see below:

    grep -o . <<< "I ♥  Gawr gura" | shuf -rn 20 | paste -sd ''
    # r♥wa raG   r ga w ♥♥
    # Guagwwu g ♥   uar♥  
    # ugIg  ♥GrG  ur rIwu 
    # ...

    use fold instead if you are aware of what exactly you are trying to do.

    fold -w 1 <<< "I ♥  Gawr gura" | shuf -rn 20 | paste -sd ''
    # IwIg  gGg  �rI ��wG 
    # G�Iw� GGa rr  aIr �G
    # G G� a u � Gur�ugw w
    # ...
  3. It will pick 10 characters by default if you haven't specified anything yet.

    ./roll.sh <<< ABC
    # BAAACBBACA
    ./roll.sh 3 <<< ABC
    # CCA
#!/bin/sh
grep -o . | shuf -rn ${1:-10} | paste -sd ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment