Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get line from file at specified byte offset

I have a file with a bunch of lines. I have a list of the bytes offsets corresponding with the start of each line. I want each line that corresponds with the byte offset. Is there a way to do this in unix, perl or python? I have to do this at a much larger scale than described.

File:

abcd
bcde
cdef

Byte Offsets:

0
10

Desired Output:

abcd
cdef
like image 674
ferrants Avatar asked Dec 21 '22 12:12

ferrants


2 Answers

with open(filename, 'r') as f:    
    for offset in offsets:
        f.seek(offset)
        print(f.readline())

References:

  • with statement
  • open
  • seek
  • readline
like image 173
unutbu Avatar answered Dec 29 '22 01:12

unutbu


Quickie perl:

my @offsets = ( 0, 10 );

open (my $data, '<', 'file.txt') || die "Can't open input: $!\n";

foreach my $offset (@offsets) 
{
    seek( $data, $offset, 0 );
    my $line = <$data>;
    print $line;
}

close $data;
like image 39
theglauber Avatar answered Dec 28 '22 23:12

theglauber