【问题标题】:Replace parts of file with 0xFF?用 0xFF 替换部分文件?
【发布时间】:2020-06-10 00:46:21
【问题描述】:

我想修改一个文件,以便从位置0x30000xDC000 的每个字节都替换为0xFF,其他所有内容都应该保持不变。

如何使用标准 Linux 工具来实现这一点?

【问题讨论】:

  • 欢迎来到 SO,在 SO 上,我们确实鼓励人们为解决自己的问题付出他们的努力,所以请在您的问题中添加相同的内容,然后让我们知道。
  • yes $'\xFF' | tr -d '\n' | dd conv=notrunc bs=1c seek=$((0x3000-1)) count=$((0xDC000)) of=FILE
  • Perl “标准” 吗? Pythonxxd?

标签: linux bash shell file binary


【解决方案1】:

这是jhnc's answer,几乎没有改进(在此答案末尾解释)。

#! /bin/bash
overwrite() {
    file="$1"; from="$2"; to="$3"; with="$4"
    yes '' | tr \\n "\\$(printf %o "$with")" |
    dd conv=notrunc bs=1 seek="$((from))" count="$((to-from))" of="$file"
}

在你的情况下,你会使用上面的函数

overwrite yourFile 0x3000 0xDC000 0xFF

开始和结束字节都是从 0 开始的。开始是包容的,结束是排斥的。示例:

$ printf 00000 > file
$ overwrite file 1 3 0x57
$ hexdump -C file
00000000  30 57 57 30 30   |0WW00|
00000005

所做的改进:

  • 修正了错误的count=... 并解释了开始和结束的解释。

  • 允许用空字节填充。
    如果你想写空字节0x00,你不能使用yes $'\x00'。空字节将代表yes 的参数字符串的结尾,使调用等效于yes ''。由于yes '' | tr -d \\n 不产生任何输出,dd 将无限期等待。
    此答案中提供的命令允许您用任何字节填充该区域(从 0x00 到 0xFF 中选择一个)。

【讨论】:

  • 干得好。在 macOS 上,使用 dd conv=notrunc bs=1 ...,因为不接受 c
  • @MarkSetchell 谢谢你的提示。我刚刚从 jhnc 复制了c。它现在已被删除,因为 POSIX documentation 明确指出 bs 无论如何是以字节为单位指定的。
  • 在我的辩护中,问题指定了 linux :-) 很好的概括。关于基于 0 或 1 的位置和 (s,e) / [s,e) / [s,e] 的问题是模棱两可的。数一数二。
【解决方案2】:

如果Perl 是您的选择,请尝试以下方法:

perl -e '
$start = 0x3000;                        # start position to overwrite
$end = 0xDC000;                         # end position to overwrite
$file = "file";                         # filename to modify (replace with your filename)

open(FH, "+< $file") or die "$file";    # open the file "$file" to both read & write with the filehandle "FH"
seek(FH, $start, 0);                    # jump to the start position
for ($i = $start; $i < $end; $i++) {    # loop over the overwrite area
    print FH "\xFF";                    # replace the byte with 0xFF
}
close(FH);
'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 2016-11-02
    • 1970-01-01
    相关资源
    最近更新 更多