skyfire
skyfire

Reputation: 247

Perl one liner to seek to offset in file

Is there a way to specify reading in file bytes that are at a position/offset within a binary file from the cmdline? (i.e. one-liners) e.g.

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

I haven't seen this and have tried using seek, sysseek, etc.

just want to experiment with pack and unpack by reading in a length of bytes at different offsets within a file.

UPDATE

In addition to the accepted answer, I just want to add the following equivalent answer but (to me) easier to remember+read

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

UPDATE2 For the purpose of doing hexdumps the following works

perl -0777 -ne '(printf "0x%02x ", $_) for (unpack "C*", substr($_, 0x1, 0x2))' input

Upvotes: 1

Views: 290

Answers (1)

ikegami
ikegami

Reputation: 385647

perl -M5.010 -0777ne'say unpack("N", substr($_, 0x20, 4))' inputfile

You're using -n, which reads a line of the file into $_. Binary files don't have lines, so we'll use -0777 to tell Perl the treat the whole file as a line. Won't work in Windows since CRLF translation will occur.


For actual seeking,

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

You can remove the line breaks if you want it all on one line.

Upvotes: 1

Related Questions