How do I use Head and Tail to print specific lines of a file

user2232423 picture user2232423 · Apr 1, 2013 · Viewed 79k times · Source

I want to say output lines 5 - 10 of a file, as arguments passed in.

How could I use head and tail to do this?

where firstline = $2 and lastline = $3 and filename = $1.

Running it should look like this:

./lines.sh filename firstline lastline

Answer

head -n XX # <-- print first XX lines
tail -n YY # <-- print last YY lines

If you want lines from 20 to 30 that means you want 11 lines starting from 20 and finishing at 30:

head -n 30 file | tail -n 11
# 
# first 30 lines
#                 last 11 lines from those previous 30

That is, you firstly get first 30 lines and then you select the last 11 (that is, 30-20+1).

So in your code it would be:

head -n $3 $1 | tail -n $(( $3-$2 + 1 ))

Based on firstline = $2, lastline = $3, filename = $1

head -n $lastline $filename | tail -n $(( $lastline -$firstline + 1 ))