本文介绍了更改大文件中的几个字节,而无需在Linux上使用bash加载内存中的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以更改大文件中的几个字节/字符?例如,寻求将x定位,然后有选择地删除一些字符,然后插入一些字符.我更喜欢用bash来做.

in bash on linux is there a way to change a few bytes/characters in a large file? for example, seek to position x and then optionally delete a few characters, and then insert a few characters. I prefer to do this in bash.

推荐答案

通常,无法对文件进行编辑"以更改字符在编辑点之后的位置...除非通过阅读和在编辑点之后重写所有字符.

In general, it is not possible to make an "edit" to a file that changes the position of characters after the edit point ... except by reading and rewriting all characters after the edit point.

其原因是文件表示方式以及文件系统API工作方式的基础.而这些反过来又来自物理存储设备的工作方式.

The reason for this is fundamental to the way that files are represented, and the way that file system APIs work. And these in turn derive from the way that the physical storage devices work.

因此,一般的解决方案需要实现以下形式(伪代码):

So a general solution would need to be implemented something like this (pseudo-code):

# Replace N bytes starting at position P with bytes B1, B2,...

open file in "random access, no truncation" mode 
seek to N + P
read remainder of file into a buffer.
seek to N
write bytes B1, B2, ...
write bytes from the buffer
close

(您可以避免将整个文件的其余部分"放入缓冲区,但是逻辑更加复杂.并且与我要解释的内容相切...)

(You could avoiding the entire "remainder of the file" into a buffer, but the logic is more complicated. And tangential to what I'm trying to explain ...)

无论如何,我还不知道可以执行上述操作的现有实用程序,但是如果愿意,您可以编写一个临时程序来执行此操作.

Anyway, I'm not aware of an existing utility that will do the above, but you could write an ad-hoc program to do that if you wanted to.

如果要替换的字节数与替换的字节数完全相同,则可以进行就地更新.根据如何覆盖二进制文件的某些字节您可以使用"dd"命令执行此操作.(答案显示了一个1字节的就地更新.)

If the number of bytes you were replacing was exactly the same as the number of replacement bytes, you could do this with an in-place update. According to How to overwrite some bytes of a binary file with dd? you can do this with the "dd" command. (The Answer demonstrates a 1 byte in-place update.)

这篇关于更改大文件中的几个字节,而无需在Linux上使用bash加载内存中的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 20:56