Raghav
Raghav

Reputation: 796

Get the contents of a line by line number in perl, awk, grep

I would like to know if it's possible to get contents of line by line number as input. For example how can I get the contents of line 314 using a tool such as perl, grep, awk.

I have few options I have tried

  1. Counting till the line number in perl and printing - not the most efficient

  2. If I know the pattern in the line find line number using grep -in "pattern" file.

But something like vim :314 is what I'm expecting using perl, awk, grep.

Upvotes: 2

Views: 2811

Answers (4)

ysth
ysth

Reputation: 98398

perl -MTie::File -we'use Tie::File; tie my @file, "Tie::File", $ARGV[0], autochomp=>0 or die "Error opening $ARGV[0]"; print $file[313]' /path/filename.txt

or using coreutils:

head -n 314 /path/filename.txt | tail -n 1

Upvotes: 1

Chris Seymour
Chris Seymour

Reputation: 85795

This is how to print a single line given a line number With awk:

$ awk 'NR==314' file

If you file is large you may want to quit after reaching the line:

$ awk 'NR==314{print;exit}' file

You could also use sed for this:

$ sed '314!d' file

Equally:

$ sed -n '314p' file

With sed to print a line by number and quit you would do:

$ sed -n '314{p;q}' file

The perl solution will be similar to the awk solution however I don't know/use perl myself. This can not be done with grep unless you use nl or cat -n firts. However you can print the line numbers of lines matching the given pattern with grep using the -n option.

From man grep:

-n, --line-number                                  (-n is specified by POSIX.)  
Prefix each line of output with the 1-based line number within its input file.

Upvotes: 4

marderh
marderh

Reputation: 1256

P ossible solution as Perl-oneliner to read filename.txt and print out line n (starting with 0!):

perl -e 'my @lines= do { local(*ARGV); @ARGV="/path/filename.txt"; <> }; print $lines[n]'

A shorter one unsing special variable $. (starting with 1):

perl -ne 'print if $. == n' filename.txt

Upvotes: 1

Greg Bacon
Greg Bacon

Reputation: 139521

perl -ne 'print if $. == 314' input

Upvotes: 3

Related Questions