如何从bash脚本替换文件中的数据?
问题描述:
我需要从bash脚本修改存储在磁盘中的二进制文件的数据。这个怎么做?如何从bash脚本替换文件中的数据?
(例如,我需要开设100字节大小的文件,并在使用0xff第50字节位置替换数据为0x00)
我试图谷歌,但无法找到答案。任何帮助表示赞赏。
谢谢。
答
Perl来救援:
#!/usr/bin/perl
use warnings;
use strict;
use Fcntl qw{ SEEK_SET SEEK_CUR };
my $pos = 50;
open my $BIN, '+<:raw', shift or die $!;
seek $BIN, $pos - 1, SEEK_SET or die "Can't seek into file.\n";
my $size = read $BIN, my $data, 1;
die "Can't read 50th byte from file.\n" unless $size;
if ("\0" eq $data) {
seek $BIN, - 1, SEEK_CUR;
print {$BIN} "\xff";
close $BIN;
} else {
warn "Nothing to replace, 50th byte isn't a zero.\n";
}
-
+<
打开在读/写模式下的文件。 -
:raw
删除任何IO层(例如,CRLF转换) -
seek
在文件句柄中回退位置。