olekb
olekb

Reputation: 648

How to update a byte in the middle of binary file in Linux shell?

When I run cmp on 2 files I get one byte difference:

cmp -l file1.dmp_byte file2.dmp
913462  0 100

How do I update byte 913462 of file file1.dmp with value 100?

Can it be done using standard Linux shell tools or Python?

Upvotes: 0

Views: 347

Answers (2)

olekb
olekb

Reputation: 648

I accepted the answer, but went for different solution

def patch_file(fn, diff):
    for line in diff.split(os.linesep):
        if line:
            addr, to_octal, _ = line.strip().split()
            with open(fn , 'r+b') as f:
                f.seek(int(addr)-1)
                f.write(chr(int (to_octal,8)))

diff="""
     3 157 266
     4 232 276
     5 272 273
     6  16  25
    48  64  57
    58 340   0
    64   1   0
    65 104   0
    66 110   0
   541  61  60
   545  61  60
   552  61  60
   559  61  60
 20508  15   0
 20509 157   0
 20510 230   0
 20526  10   0
 20532  15   0
 20533 225   0
 20534 150   0
913437 226   0
913438  37   0
913454  10   0
913460   1   0
913461 104   0
913462 100   0
"""

patch_file(f3,diff)     

Upvotes: 0

dorian
dorian

Reputation: 6272

In Python, you could use a memory-mapped file:

import mmap
with open('file1.dmp', 'r+b') as fd:
    mm = mmap.mmap(fd.fileno(), 0)
    mm[913462] = chr(100)
    mm.close()

Upvotes: 1

Related Questions