Home > Software design >  How can I append a variable number of hexadecimal bytes to a file?
How can I append a variable number of hexadecimal bytes to a file?

Time:10-22

I have the following code

printf '\xFF%.s' {1..10} >SomeFile.bin

Which lets me write 10 bytes containing 0xFF to a file.

But I would like to write a varying number of bytes to that file. However, curly brace sequences do not work with variables.

Is there a way to do the same operation using a variable instead of the hardcoded 10 repetitions?

CodePudding user response:

Sticking close to OP's current code:

x=10
printf '\xFF%.s' $(seq $x) > SomeFile.bin

For ever larger values of x the seq approach requires ever larger quantities of cpu and memory so at some point it may be worthwhile to look at a looping construct, eg, awk/for-loop:

awk -v x="9999999" 'BEGIN {for (i=1;i<=x;i  ) printf "\xff"}' > SomeFile.bin

For x=9999999:

  • printf/seq - 48 seconds to run; memory fluctuated with a max of 950 MB
  • awk/for-loop - 3 seconds to run; negligible memory usage

NOTE: my system: cygwin (running in a VM), GNU bash 4.4.12 (printf builtin), GNU seq 8.26, GNU awk 5.1.1

  •  Tags:  
  • bash
  • Related