-1

I need to modify the data of a binary file stored in disk, from bash script. How to do this?

(For example, I need to open a file with 100 byte size and replace data 0x00 at 50th byte position with 0xff)

I tried google, but unable to find the answer. Any help is appreciated.

Thank you.

NeonGlow
  • 1,659
  • 4
  • 18
  • 36

1 Answers1

1

Perl to the rescue:

#!/usr/bin/perl
use warnings;
use strict;

use Fcntl qw{ SEEK_SET SEEK_CUR };

my $pos = 50;

open my $BIN, '+<:raw', shift or die $!;
seek $BIN, $pos - 1, SEEK_SET or die "Can't seek into file.\n";

my $size = read $BIN, my $data, 1;
die "Can't read 50th byte from file.\n" unless $size;

if ("\0" eq $data) {
    seek $BIN, - 1, SEEK_CUR;
    print {$BIN} "\xff";
    close $BIN;
} else {
    warn "Nothing to replace, 50th byte isn't a zero.\n";
}
  • +< opens the file in the read/write mode.
  • :raw removes any IO layers (e.g. CRLF translation)
  • seek rewinds the position in a filehandle.
choroba
  • 231,213
  • 25
  • 204
  • 289