Archive for the ‘linux’ Category

vi: edit files in binary mode

July 30, 2015

This post shows how to edit files in binary mode.

  • Create a binary file
  • $ dd if=/dev/zero of=a.out bs=16 count=2
    2+0 records in
    2+0 records out
    32 bytes (32 B) copied, 8.8878e-05 s, 360 kB/s
    
  • Edit the file in binary mode
  • $ vi -b a.out
    ^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@
    
  • Feed buffer contents into the standard input of xxd and replace the original buffer with the standard output of xxd
  • :%!xxd
    0000000: 0000 0000 0000 0000 0000 0000 0000 0000  ................
    0000010: 0000 0000 0000 0000 0000 0000 0000 0000  ................
    
  • Update the second byte as 0xab
  • 0000000: 00ab 0000 0000 0000 0000 0000 0000 0000  ................
    0000010: 0000 0000 0000 0000 0000 0000 0000 0000  ................
    
  • Feed buffer contents into the standard input of xxd -r and replace the original buffer with the standard output of xxd -r
  • :%!xxd -r
    ^@?^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@
    
  • Save and close the file
  • :wq
    
  • xxd shows the binary file is updated as expected
  • $ xxd a.out
    0000000: 00ab 0000 0000 0000 0000 0000 0000 0000  ................
    0000010: 0000 0000 0000 0000 0000 0000 0000 0000  ................
    
    Advertisements

    %d bloggers like this: