menu

Questions & Answers

select the second line to last line of a file

How can I select the lines from the second line to the line before the last line of a file by using head and tail in unix?

For example if my file has 15 lines I want to select lines from 2 to 14.

Comments:
Answers(3) :
perl -ne 'print if($.!=1 and !(eof))' your_file

tested below:

> cat temp
1
2
3
4
5
6
7
> perl -ne 'print if($.!=1 and !(eof))' temp
2
3
4
5
6
> 

alternatively in awk you can use below:

awk '{a[count++]=$0}END{for(i=1;i<count-1;i++) print a[i]}' your_file
tail -n +2 /path/to/file | head -n -1

To print all lines but first and last ones you can use this awk as well:

awk 'NR==1 {next} {if (f) print f; f=$0}'

This always prints the previous line. To prevent the first one from being printed, we skip the line when NR is 1. Then, the last one won't be printed because when reading it we are printing the penultimate!

Test

$ seq 10 | awk 'NR==1 {next} {if (f) print f; f=$0}'
2
3
4
5
6
7
8
9