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
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