【问题标题】:How to substitute/replace bytes in binary file with shell如何用shell替换/替换二进制文件中的字节
【发布时间】:2013-03-12 13:49:48
【问题描述】:

是否可以在循环中使用 dd 将二进制文件 myfile 中的字节从一个特定位置替换到另一个位置,还是使用另一个命令更方便?

这个想法是在循环中用 position1 的块 A 替换位置 position2 的块 B .

伪代码

  @ l = 0

  while (l <= bytelength of myfile)
      copy myfile (from position1 to A+position1)  myfile from (position2 to B+position2)
      @ position1 = position1+steplength
      @ position2 = position2+steplength
      @ l = l+steplength

  end

【问题讨论】:

  • 虽然可能,但我不会使用 shell 命令语言来进行这种类型的文件操作。使用对此类文件 I/O 提供更好支持的语言。无论哪种情况,您是覆盖position2 处的字节,还是只是重新排列文件中的字节顺序?
  • 如果可能我想覆盖它们...

标签: shell byte block dd substitution


【解决方案1】:

文本文件中的以下代码行将大致完成(我认为)您要求的操作:将文件从一个位置复制到另一个位置,但将一个位置的字节块替换为另一个位置的块;它根据要求使用dd。但是,它确实创建了一个单独的输出文件——这对于确保没有冲突是必要的,无论“输入”块是否出现在“替换”块之前或之后。请注意,如果 A 和 B 之间的距离小于要替换的块的大小,它将不会执行任何操作 - 这将导致重叠,并且不清楚您是否希望重叠区域中的字节为“结束A”或“A 副本的开头”。

将其保存在名为 blockcpy.sh 的文件中,并更改权限以包含 execute(例如 chmod 755 blockcpy.sh)。运行它

./blockcpy.sh inputFile outputFile from to length

请注意,“from”和“to”偏移量的基数为零:因此,如果要复制从文件开头开始的字节,from 参数为 0

这是文件内容:

#!/bin/bash
# blockcpy file1 file2 from to length
# copy contents of file1 to file2
# replacing a block of bytes at "to" with block at "from"
# length of replaced block is "length"
blockdif=$(($3 - $4))
absdif=${blockdif#-}
#echo 'block dif: ' $blockdif '; abs dif: ' $absdif
if [ $absdif -ge $5 ]
  then
    # copy bytes up to "to":
    dd if=$1 of=$2 bs=$4 count=1 status=noxfer 2>0
    # copy "length" bytes from "from":
    dd bs=1 if=$1 skip=$3 count=$5 status=noxfer 2>0 >> $2
    # copy the rest of the file:
    rest=$((`cat $1 | wc -c` - $4 - $5))
    skip=$(($4 + $5))
    dd bs=1 if=$1 skip=$skip count=$rest status=noxfer 2>0 >> $2
    echo 'file "'$2'" created successfully!'
  else
    echo 'blocks A and B overlap!'
fi

2&gt;0 "'nix magic" 抑制来自 stderr 的输出,否则会显示在输出中(类型:“16+0 records in”)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-24
    • 2019-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 2017-07-25
    • 2017-12-07
    相关资源
    最近更新 更多