Perl 一行在文件中寻找偏移量

Perl one liner to seek to offset in file

有没有一种方法可以指定从 cmdline 读取二进制文件中 position/offset 处的文件字节? (即单线) 例如

perl -ne <...seek n bytes into file... do stuff...> inputfile

我还没有看到这个,并尝试使用 seek、sysseek 等

只是想通过读取文件中不同偏移量的字节长度来试验 packunpack

更新

除了已接受的答案外,我只想添加以下等效答案但(对我来说)更容易记住+阅读

perl -lne 'BEGIN{$/=undef, $offset=1, $len=2} print unpack("H*", substr($_, $offset, $len))' input

更新2 为了进行 hexdumps 以下工作

perl -0777 -ne '(printf "0x%02x ", $_) for (unpack "C*", substr($_, 0x1, 0x2))' input
perl -M5.010 -0777ne'say unpack("N", substr($_, 0x20, 4))' inputfile

您正在使用 -n,它将文件的一行读入 $_。二进制文件没有行,所以我们将使用 -0777 告诉 Perl 将整个文件视为一行。在 Windows 中不起作用,因为会发生 CRLF 转换。


实际求,

perl -M5.010 -MFcntl=SEEK_SET -e'
   open(my $fh, "<:raw", $ARGV[0]) or die $!; 
   seek($fh, 0x20, SEEK_SET) or die $!;
   local $/ = ;
   length( my $buf = <$fh> ) == 4 or die "Error";
   say unpack("N", $buf);
' inputfile

如果您希望所有内容都在一行中,您可以删除换行符。