简体   繁体   中英

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.

tail -n +2 /path/to/file | head -n -1
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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM