Create a file of a specific size with random printable strings in bash

后端 未结 6 793
陌清茗
陌清茗 2021-01-13 22:27

I want to create a file of a specific size containing only printable strings in bash.

My first thought was to use /dev/urandom:

dd if=/d         


        
6条回答
  •  暖寄归人
    2021-01-13 22:34

    You can do it in awk way and customize character set.

    This solution is dedicated for Windows bash users - MINGW, because there is no dd, random tools at default MINGW environment.

    random_readable.sh Bash script that randomize N characters from defined alphabet:

    #!/bin/sh
    
    if [ -z $1 ]; then
        echo "Pass file size as initial parameter"
        exit
    fi
    
    SIZE=$1
    seed=$( date +%s )
    
    awk -v size="$SIZE" -v seed="$seed" '
    # add characters from range (a .. b) to alphabet
    function add_range(a,b){
        idx=a;
        while (idx <= b) {
            alphabet[idx] = sprintf("%c",idx)
            idx+=1
        }
    }
    BEGIN{
        srand(seed);  
        NUM=size;  
        idx=0;  
    
        # creating alfphabet dictionary
        add_range(32,126)   # all printable
        ## uncomment following lines to random [a-zA-Z0-9]
        # add_range(48,57)    # numbers
        # add_range(65,90)    # LETTERS
        # add_range(97,122)   # letters
        # add_range(33,47)    # operators: !"# .. etc
    
        # alfphabet to alphanums array
        idx=0
        for (k in alphabet){
            alphanums[idx]=alphabet[k]
            idx+=1
        }
        alphabet_len = idx
        i=0
    
        # and iterate to random some characters
        idx =0
        while (idx < NUM){                         
            dec =0
            char_idx=int(rand() * alphabet_len)
            char = alphanums[char_idx]
            printf("%s",alphanums[char_idx])
            idx+=1
        }  
    }  
    ' 
    

    Creating file:

    random_readable.sh 100 > output.txt
    

提交回复
热议问题