Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

one-liner: print all lines except the last 3?

I would like to simulate GNU's head -n -3, which prints all lines except the last 3, because head on FreeBSD doesn't have this feature. So I am thinking of something like

seq 1 10 | perl -ne ...

Here I have used 10 lines, but it can be any number larger than 3.

Can it be done in Perl or some other way on FreeBSD in BASH?

A super primitive solution would be

seq 1 10 | sed '$d' | sed '$d' | sed '$d'
like image 512
Sandra Schlichting Avatar asked Sep 20 '13 18:09

Sandra Schlichting


1 Answers

seq 1 10 | perl -e '@x=("")x3;while(<>){print shift @x;push @x,$_}'

or

perl -e '@x=("")x3;while(<>){print shift @x;push @x,$_}' file

or

command | perl -pe 'BEGIN{@x=("")x3}push @x,$_;$_=shift @x'
perl -pe 'BEGIN{@x=("")x3}push @x,$_;$_=shift @x' file
like image 159
mob Avatar answered Oct 10 '22 09:10

mob