4

I'm generating a binary file as test data for a piece of software. The test data should consist of a long array of the same byte. If it was a zero byte I would use /dev/zero. Is there a command to transform the zeros from there into another byte, or a command to do a similar thing?

I came up with this bash script, but this solution doesn't feel ideal. It can only generate a fixed number of bytes. There is surely a way to do this with a simpler script.

for i in $(seq 5); do
    echo $'\x10'
done
terdon
  • 242,166
jacwah
  • 537

1 Answers1

4

To use /dev/zero to generate n characters of your choice:

head -c "$n" /dev/zero | sed 's/\x00/a/g'

where you should replace the a with whatever the character was that you wanted.

For example:

$ n=50; head -c "$n" /dev/zero | sed 's/\x00/a/g'
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

This assumes that you have a sed, such as GNU sed, that is capable of understanding \x00.

Alternatively, tr could be used:

$ n=50; head -c "$n" /dev/zero | tr '\00' 'a'
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
John1024
  • 74,655
  • 2
    This is much more sensible than the answers in the duplicate question. – jacwah Jul 17 '15 at 21:25
  • 2
    @jacwah - in fact, no. sed is a terrible direction to take this - though they are presented as such, tr and sed in this capacity are by no means equal. the nearest they could come is w/ sed y/\\x00/a/, but then you still have to work w/ sed's \newline buffer. tr should be preferred in every case - sed should never have entered into this at all. head -c doesn't make a lot of sense here, either. Just do: printf %050s | tr \ a. See this which that other, in my opinion, should have been made a duplicate of in the first place. – mikeserv Jul 17 '15 at 22:34