在另一个文件中查找一个文件的内容,并替换为 FF

在另一个文件中查找一个文件的内容,并替换为 FF

我有一个名为 rockx.dat 的二进制文件,以及一堆其他二进制文件 rockx_#.pmf。

我想找到dat文件中pmf文件的内容,并将其替换为FF。所以如果pmf文件是500字节,我想用500 FF字节替换它。

答案1

您可以用于xxd您的应用程序。
为了处理二进制文件,您需要多个步骤:

#!/bin/bash
file_orig="rockx.dat"
file_subst="rockx_0.pmf"
# could use tmpfile here
tmp_ascii_orig="rockx.ascii"
tmp_ascii_subst="subst.ascii"

# convert files to ascii for further processing
xxd -p "${file_orig}" "${tmp_ascii_orig}"
xxd -p "${file_subst}" "${tmp_ascii_subst}"

# remove newlines in converted files to ease processing
sed -i ':a;N;$!ba;s/\n//g' "${tmp_ascii_orig}"
sed -i ':a;N;$!ba;s/\n//g' "${tmp_ascii_subst}"

# create a 0xff pattern file for pattern substitution
ones_file="ones.ascii"
dd if=<(yes ff | tr -d "\n") of="${ones_file}" count="$(($(stat -c %s "${tmp_ascii_subst}") - 1))" bs=1

# substitute the pattern in the original file
sed -i "s/$(cat "${tmp_ascii_subst}")/$(cat "${ones_file}")/" "${tmp_ascii_orig}"

# split the lines again to allow conversion back to binary
sed -i 's/.\{60\}/&\n/g' "${tmp_ascii_orig}"

# convert back
xxd -p -r "${tmp_ascii_orig}" "${file_orig}"

有关换行符替换的更多信息,请查看这里
有关模式文件创建的更多信息,请查看这里
有关行分割的信息请查看这里
有关xxdhve 的信息请查看联机帮助页。

请注意,这仅适用于一种模式替换,但应该可以更改它以提供多个文件的多个替换,而无需付出很大的努力。

相关内容