raphink
raphink

Reputation: 3665

Get line number from character position

How can I locate the line where character n in file is located?

For example, how can I know where character 5347 is located in a given file?

Upvotes: 3

Views: 734

Answers (2)

Marco De Lellis
Marco De Lellis

Reputation: 1189

If you are reading from a filehandle line by line with line input operator, special variable $. gives current line.

Here is some sample code: it reads a file line, counting characters with $pos.

#!/usr/bin/env perl

use v5.12;
use strict;

open my $fh, '<', 'file.txt';

my $reference = 5347;
my $pos       = 0;

do {
    $pos += length <$fh>;
 } while ( $pos < $reference );

say $.;

Upvotes: 5

e.dan
e.dan

Reputation: 7475

This lightly tested code seemed to me to do the job:

my $desired = 5347;
my $char_count = 0;
while ( <$fh> ) {
    $count += length;
    if ( $count >= $desired ) {
        print $. . $/;
        last;
    }
}

Of course it assumes that $fh is an already opened filehandle that hasn't been read from yet.

Also note that it counts characters, not bytes, which is what you said, but might not have been what you meant.

Upvotes: 3

Related Questions