$ export MAX=6;tac YOUR-FILE.txt | perl -lane '$seen{$_}++ or push @out,$_ for @F}{print join(q| |,@out[0..$ENV{MAX}||$#out])' 21 22 23 24 17 18 19