Displaying selected lines using head and tail command

Viewed 556

How can I use the ‘head’ and ‘tail’ commands with piping to display only lines 2 and 3 from my selected file 'imaginaryfile' (which has 10 lines)?

What I've tried so far:

>$ head -n  3 imaginaryfile | tail -n 2 > > (head -n 1) > > (tail -n 1)

The output for line 3 comes, but I didn't get an output of line 2. What can I do to correct this and get an output of line 2 and line3?

3 Answers
head -3 file | tail -n +2

head will print the first 3 lines. This output will be the input for the tail command which will start printing from the second line to the end.

From man tail

-n, --lines=[+]NUM output the last NUM lines, instead of the last 10; or use -n +NUM to output starting with line NUM

You could do this in simple awk.

awk '
FNR>=2 && FNR<=3{
  print
  if(FNR==3){
    exit
  }
}
' Input_file


Giving ranges in variable in awk from where to where you want to print.

awk -v from="2" -v till="3" '
FNR>=from && FNR<=till{
  print
  if(FNR==till){
    exit
  }
}
' Input_file

For printing selected lines, use any of these Perl one-liners:

# Explicit and simple code:
perl -ne 'print if $. >= 2 && $. <= 3' input_file

# Shorter, but less explicit code:
perl -ne 'print if 2..3' input_file

# Longer and more complex code, but runs faster for larger files, 
# because the script exits after line 3:
perl -ne 'next if $. < 2; last if $. > 3; print;' input_file

Example:

seq 1 10 | perl -ne 'print if $. >= 2 && $. <= 3'
2
3

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-n : Loop over the input one line at a time, assigning it to $_ by default.

$. : current input line number.

SEE ALSO:
perldoc perlrun: how to execute the Perl interpreter: command line switches
perldoc perlvar: Perl predefined variables

Related