You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从输入文件指定位置取字节插入到目标文件指定偏移位置?

我来帮你搞定这个需求——你想要从源文件的指定位置复制特定数量的字节,插入到目标文件的指定偏移位置,对吧?先说说你之前思路里的问题:

你的第一个命令用了xxd,但xxd是把二进制数据转换成十六进制文本输出的,这样管道给dd写入的不是原始字节,而是文本内容,完全达不到预期效果。而第二个脚本用了oflag=append,这个参数只能在文件末尾追加内容,没办法实现“插入到中间指定位置”的操作。

下面给你提供两种可行的方案,一个是手动分步执行的命令,另一个是封装好的脚本:

手动分步执行(适合临时操作)

  1. 先从源文件提取需要的字节到临时文件:
dd if=inFile of=temp_bytes bs=1 skip=$startOffset count=$numBytes

这里bs=1表示按字节操作,skip=$startOffset跳过源文件开头的$startOffset字节,count=$numBytes只读取$numBytes个字节。

  1. 保存目标文件中从插入位置开始的后半部分内容:
dd if=fileToModify of=temp_tail bs=1 skip=$location
  1. 将提取的字节写入目标文件的指定位置(这一步会覆盖后面的内容,但我们已经备份了后半部分):
dd if=temp_bytes of=fileToModify bs=1 seek=$location conv=notrunc

conv=notrunc确保目标文件不会被截断。

  1. 把备份的后半部分追加到目标文件末尾:
dd if=temp_tail of=fileToModify bs=1 conv=notrunc oflag=append
  1. 最后清理临时文件:
rm temp_bytes temp_tail

封装好的自动化脚本(适合重复使用)

这个脚本会自动处理输入参数、做基本的合法性检查,更方便使用:

#!/bin/bash

# 获取用户输入
read -p "Enter source file :> " srcFile
read -p "Enter start offset in source (bytes, 0-based):> " srcOffset
read -p "Enter number of bytes to copy:> " byteCount
read -p "Enter target file :> " targetFile
read -p "Enter insert offset in target (bytes, 0-based):> " targetOffset

# 检查文件是否存在
[ ! -f "$srcFile" ] && echo "Error: Source file $srcFile does not exist!" && exit 1
[ ! -f "$targetFile" ] && echo "Error: Target file $targetFile does not exist!" && exit 1

# 检查输入是否为数字
if ! [[ "$srcOffset" =~ ^[0-9]+$ && "$byteCount" =~ ^[0-9]+$ && "$targetOffset" =~ ^[0-9]+$ ]]; then
    echo "Error: Offsets and byte count must be positive integers!"
    exit 1
fi

# 检查源文件是否有足够的字节可读
srcSize=$(stat -c%s "$srcFile")
if [ $((srcOffset + byteCount)) -gt $srcSize ]; then
    echo "Error: Source file is only $srcSize bytes. Cannot read $byteCount bytes from offset $srcOffset."
    exit 1
fi

# 检查目标偏移是否合理
targetSize=$(stat -c%s "$targetFile")
if [ $targetOffset -gt $targetSize ]; then
    echo "Error: Target file is only $targetSize bytes. Cannot insert at offset $targetOffset."
    exit 1
fi

# 创建安全的临时文件
tempBytes=$(mktemp)
tempTail=$(mktemp)

# 执行字节提取、备份、插入操作
dd if="$srcFile" of="$tempBytes" bs=1 skip="$srcOffset" count="$byteCount" 2>/dev/null
dd if="$targetFile" of="$tempTail" bs=1 skip="$targetOffset" 2>/dev/null
dd if="$tempBytes" of="$targetFile" bs=1 seek="$targetOffset" conv=notrunc 2>/dev/null
dd if="$tempTail" of="$targetFile" bs=1 conv=notrunc oflag=append 2>/dev/null

# 清理临时文件
rm "$tempBytes" "$tempTail"

echo "✅ Success! Inserted $byteCount bytes from $srcFile (offset $srcOffset) into $targetFile at offset $targetOffset."

把上面的内容保存成insert_bytes.sh,然后给它加执行权限:chmod +x insert_bytes.sh,运行它按照提示输入参数就行。

内容的提问来源于stack exchange,提问作者0siris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:03:41