ferrants
ferrants

Reputation: 631

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

Upvotes: 4

Views: 5038

Answers (5)

theglauber
theglauber

Reputation: 29605

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;

Upvotes: 4

unutbu
unutbu

Reputation: 879401

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

References:

Upvotes: 5

ferrants
ferrants

Reputation: 631

When I ended up with (thanks to unutbu)

#!/usr/bin/python
f = open(file_name, 'r')
offsets = [0,10]
for offset in offsets:
    f.seek(offset)
    print f.readline().strip()

Upvotes: 1

BenTrofatter
BenTrofatter

Reputation: 2158

This should do it.

def get_lines_by_offset(filename, *offsets):
    with open(filename, "r") as fp:
        results = []
        for offset in offsets:
            fp.seek(offset)
            results.append(fp.readline().strip())
    return results

Upvotes: 1

tripleee
tripleee

Reputation: 189367

seek() to the required byte position, then read. This should be easy from Python and Perl, and doable from shell script (I'm thinking dd).

Upvotes: 1

Related Questions