8

How can I change the first byte of multiple files in Linux? Willing to use perl/awk/sed/whatever. This must work correctly on binary files (i.e. not change any other bytes).

2
  • are you sure you mean byte? (a byte is a unit of data that is eight binary digits long). If you change the first byte of a file Im guessing you will corrupt the file. Are you referring to changing the first char of the filename?
    – DataPimp
    Mar 17, 2010 at 17:18
  • No, I meant what I said. I need to invalidate the data for a bunch of torrents that my client has marked as completed, but the tracker doesn't agree. I figure the best way is to change the data as little as possible and force my client to re-check the data. Then it'll download at most one piece from each torrent, and tell the tracker the torrent is done. Mar 17, 2010 at 17:20

2 Answers 2

18

You can do something like,

echo -ne \\xFF | dd conv=notrunc bs=1 count=1 of=$YOURFILE

-n => do not output the trailing newline
-e => enable interpretation of backslash escapes

Replacing FF with your hex value.

Try it first though :)

3
  • 1
    Nice and simple, works fine according to my testing. Is that easily adaptable to changing a byte other than the first? I played around with it a little but couldn't get it to work. Mar 17, 2010 at 20:10
  • 3
    @jnylen It should be adaptable to changing an arbitrary byte other than the first as well, the seek=<nblocks> option to dd is what you're looking for. Mar 19, 2010 at 10:51
  • @Kjetil: thanks, that worked... I'd vote your comment up if I had 2 more reputation points :p Mar 20, 2010 at 19:14
-1

compile this with gcc -o w1stb w1stb.c and use it like ./w1stb <file> <byte>:

#include <stdio.h>
int main(int argc, const char *argv[]) {

   int i;
   FILE* f;
   unsigned char b;

   if (argc < 3) {
       printf("usage: w <filename> <byte>\n");
       return 1;
   }

   i = atoi(argv[2]);

   if (i < 0) {
       printf("error, negative byte\n");
       return 2;
   }

   if (i > 255) {
       printf("error, to big byte\n");
       return 3;
   }

   f = fopen(argv[1], "w");
   if (!f) {
       printf("error, can't open file\n");
       return 4;
   }

   b = (unsigned char)i;
   fwrite(&b, 1, 1, f);
   fclose(f);

   return 0;
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .