kenorb kenorb - 6 months ago 17
Bash Question

How to change double value at specific offset in the file from shell script?

I've got 5 double values stored in binary file, in the following way:

perl -e "print pack('d5', (0.001, 0.002, 0.003, 0.004, 0.005))" > file.bin


and I'd like to change 5th value from
0.005
into
0.008
in the already existing file.

I'm aware that I can read the double by using GNU
od
, like:

$ od -tfD -An -j32 -N8 file.bin | xargs
0.005


but how can I modify one of these values in a simple way in shell?

Does GNU
od
has ability to change it, or I've to use other utilities (like
xxd
), or I should use perl?

Answer
perl -i -0777pe'my @n = unpack("d5", $_); $n[4] = 0.008; $_ = pack("d5", @n);' file.bin

-or-

perl -i -0777pe'substr($_, 4*8, 8, pack("d", 0.008))' file.bin

Where:

  • -i - make change directly in the file,
  • -0777 - changes the line separator to undef, allowing to slurp the file by feeding all the lines to Perl in one go,
  • -p - places a printing loop around your command,
  • -e '...' - allows you to provide the program from the argument
Comments