如何使用 Bash 在二进制文件中查找 2 个字节,增加它们的值并替换?

pio*_*kkr 8 text-processing conversion binary replace

我试图在二进制文件中找到两个字节,然后增加这两个字节的值并在文件中替换它们。这两个字节位于位置 0x82-0x83。现在我已经使用这个成功提取了这两个字节:

#!/usr/bin/env bash
BYTES=$(tail -c +131 "$1" | head -c 2)
Run Code Online (Sandbox Code Playgroud)

这些字节具有值:1B 1F. 我坚持:

  1. 如何将字节转换为整数?应该是6943十进制。
  2. 如何将二进制数据附加/回显到文件
  3. 如何在位置 0x82-0x83 的文件中写入增加的字节。我可以使用head -c 130 original.bin >> new_file.bin && magic_command_writing_bytes_to_file >> new_file.bin && tail -c +133 original.bin,但必须有更好的方法。

我可以在 PHP 中做到这一点,它应该更容易,但我对如何在 bash 中做到这一点很感兴趣。

fro*_*utz 7

用这个文件测试:

$ echo hello world > test.txt
$ echo -n $'\x1b\x1f' >> test.txt
$ echo whatever >> test.txt
$ hexdump -C test.txt 
00000000  68 65 6c 6c 6f 20 77 6f  72 6c 64 0a 1b 1f 77 68  |hello world...wh|
00000010  61 74 65 76 65 72 0a                              |atever.|
$ grep -a -b --only-matching $'\x1b\x1f' test.txt 
12:
Run Code Online (Sandbox Code Playgroud)

所以在这种情况下1B 1F是在位置12