Search code examples
bashfilesh

bash command to replace all occurrences in a file with null bytes


Suppose there is a file named example_file, let's assume it's binary.

I want to replace all occurrences of the string example_str in it with the corresponding sequence of null bytes (\0), so that each character in the occurrence is replaced by a null byte. (explicitly specifying \0\0\0\0\0\0\0\0\0\0\0 is not an option because (1) it's inconvenient, (2) I would like to use this command multiple times for different strings)

Is there a bash command to achieve this? I'd prefer it to be as concise and straightforward as possible.


Solution

  • perl -0777spe'BEGIN { $r = "\0" x length($s) } s/\Q$s/$r/g' -- -s=example_str
    

    Notes:

    • This loads the entire file into memory.

    • This works for any substring. It can contain any "special" character except NULs since they can't be passed a parameters. You'd have to hardcode the pattern if you want to pass NULs,

      perl -0777pe'
         BEGIN {
            $s = "\0\1\2\0\1\2";
            $r = "\0" x length($s);
         }
         s/\Q$s/$r/g;
      '
      

      or use some form of encoding.

      perl -0777spe'
         BEGIN {
            $s = pack "H*", $s;
            $r = "\0" x length($s);
         }
         s/\Q$s/$r/g;
      ' -- -s=000102000102   # Hex
      
    • See Specifying file to process to Perl one-liner. Any use of -i would have to be placed before the --.

    Example

    $ printf 'fooqwebar\n' >file
    
    $ perl -0777spe'BEGIN { $r = "\0" x length($s) } s/\Q$s/$r/g' -i -- -s=qwe file
    
    $ cat -vT file
    foo^@^@^@bar