二进制 sed 替换
我试图在二进制文件中进行 sed 替换,但我开始相信这是不可能的。本质上我想做的类似于以下内容:
sed -bi "s/\(\xFF\xD8[[:xdigit:]]\{1,\}\xFF\xD9\)/\1/" file.jpg
我希望实现的逻辑是:扫描二进制文件直到十六进制代码 FFD8
,继续读取直到 FFD9
,并只保存它们之间的内容(丢弃前后的垃圾,但包括 FFD8
和 FFD9
作为文件的保存部分)
有没有好的方法可以做到这一点?即使不使用 sed?
编辑:我只是在玩弄,找到了最干净的方法(IMO)。我知道这个 grep 语句会表现得很贪婪。
hexdump -ve '1/1 "%.2x"' dirty.jpg | grep -o "ffd8.*ffd9" | xxd -r -p > clean.jpg
I was attempting to do a sed
replacement in a binary file however I am beginning to believe that is not possible. Essentially what I wanted to do was similar to the following:
sed -bi "s/\(\xFF\xD8[[:xdigit:]]\{1,\}\xFF\xD9\)/\1/" file.jpg
The logic I wish to achieve is: scan through a binary file until the hex code FFD8
, continue reading until FFD9
, and only save what was between them (discards the junk before and after, but include FFD8
and FFD9
as the saved part of the file)
Is there a good way to do this? Even if not using sed
?
EDIT: I just was playing around and found the cleanest way to do it IMO. I am aware that this grep statement will act greedy.
hexdump -ve '1/1 "%.2x"' dirty.jpg | grep -o "ffd8.*ffd9" | xxd -r -p > clean.jpg
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
bbe 是“用于二进制文件的 sed”,对于大型二进制文件应该比十六进制转储更有效/重建。
其使用示例:
有关手册页的更多信息。
bbe is a "sed for binary files", and should work more efficiently for large binary files than hexdumping/reconstructing.
An example of its use:
Further information on the man page.
老问题,但是,
可能是最简单、最可靠的解决方案。与OP中的编辑类似。
Old question, but,
is probably the simplest and most reliable solution. Similar to the edit in the OP.
sed 或许可以做到这一点,但可能会很棘手。这是一个执行相同操作的 Python 脚本(请注意,它会就地编辑文件,我假设您希望根据 sed 脚本执行此操作):
sed might be able to do it, but it could be tricky. Here's a Python script that does the same thing (note that it edits the file in-place, which is what I assume you want to do based on your sed script):
有没有好的方法来做到这一点
是的,当然可以使用图像编辑工具,例如 ImageMagick 中的图像编辑工具(在网上搜索 linux jpeg 、 exif 编辑器等),它知道如何编辑 jpg 元数据。我相信您一定能找到一款适合您的工具。不要试图以困难的方式做到这一点。 :)
Is there a good way to do this
yes of course, use an image editing tool such as those from ImageMagick (search the net for linux jpeg , exif editor etc) that knows how to edit jpg metadata. I am sure you can find one tool that suits you. Don't try to do this the hard way. :)
另外,如果未安装 Python,此 Perl 可能会工作(未经测试,买者自负)...
您需要添加
binmode(FILE); binmode(STDOUT);
(在 DOS 或 VMS 上,在open()
调用之后) - 在 Unix 上不需要。Also, this Perl might work (not tested, caveat emptor)... if Python is not installed :)
You need to add
binmode(FILE); binmode(STDOUT);
on DOS or VMS after theopen()
call - not needed on Unix.