8

I need to create a binary file that is filled only with 11111111.

I only know how to create zero-filled binary with

dd if=/dev/zero bs=18520 count=1

Could you please say to me what a command in pipeline should I use to fill the bin with 1? How can I use awk in this case?

1
15

Probably easiest to use tr to convert the zeroes from /dev/zero to whatever you want, and then cut to length using dd or head or such.

This would write 18520 bytes with all bits ones, so value 0xff or 255, or 377 in octal as the input must be:

< /dev/zero tr '\000' '\377' | head -c 18520 > test.bin

(To convert from hex or decimal to octal, you could use printf "%o\n" 0xff or such. )


To produce streams of longer than one-byte strings, I'd use Perl:

perl -e '$a = "abcde" x 1024; print $a while 1' | head ...

(Of course you could use "\xff" or "\377" there, too. I used the repetition operator x 1024 there mostly to avoid minimally small writes. Changing it may or may not affect the performance of that.)

4
  • 1
    @DisplayName: for string abcde without using perl, use yes: yes "abcde" | tr -d '\n' ... – Olivier Dulac Apr 20 at 12:08
  • @OlivierDulac, d'oh, I've really been slow here. Using yes actually crossed my mind before, but I got stuck at the mandatory newline... yes $'\xff' | tr -d '\n' | ... would also work for the all-ones in shells that support $''. – ilkkachu Apr 20 at 12:18
  • I'd certainly not qualify you as slow ^^. And having different options (suxh as perl) is always welcomed. Feel free to add the yes variant as well if you want. – Olivier Dulac Apr 20 at 12:24
  • It's (very) slightly more efficient to head or dd first in the pipe, then tr after. – Toby Speight Apr 21 at 12:18
13

Don't use dd bs=…: it isn't reliable. Either use ibs=1 obs=1 or use less error-prone tools. Most head implementations can count bytes:

</dev/zero head -c 18520

If you want a file filled with a single byte other than zero, change the byte value with tr. For all-bits-one:

</dev/zero head -c 18520 | tr '\0' '\377'
1

to answer your question specifically, using dd will work great with tr in a pipe

dd if=/dev/zero bs=18520 count=1 | tr '\000' '1' > test.bin

however, you should clarify the scope of this in order for one to give you a more relevant answer

1
  • 4
    1 is ascii character 1, 0x31, so the file will be filled with bits 00110001 repeated. – Paul_Pedant Apr 19 at 22:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.