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

后端 未结 6 788
陌清茗
陌清茗 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:36

    What about this?

    size=1048576 # 1MB
    fname="strings.txt"
    
    while read line ; do
        # Append strings to the file ...
        strings <<< "${line}" >> "${fname}"
        fsize="$(du -b "${fname}" | awk '{print $1}')"
        # ... until it is bigger than the desired size
        if [ ${fsize} -gt ${size} ] ; then
            # Now truncate the file to the desired size and exit the loop
            truncate -s "${size}" strings.txt
            break
        fi 
    done < /dev/urandom
    

    I admit that it is not very efficient. I faster attempt would be to use dd:

    size=1048576
    fname="strings.txt"
    
    truncate -s0 "${fname}"
    
    while true ; do
        dd if=/dev/urandom bs="${size}" count=1 | strings >> "${fname}"
        fsize="$(du -b "${fname}" | awk '{print $1}')"
        if [ ${fsize} -gt ${size} ] ; then
            truncate -s "${size}" strings.txt
            break
        fi
    done
    

提交回复
热议问题