Removing top few and bottom few rows in a file

Hi,
I have a requirement where I need to delete given number of top and bottom rows in a flat file which has new line as its delimiter.

For ex: if top_rows=2 & bottom_rows=1

Then in a given file which looks like:

New York
DC
LA
London
Tokyo
Prague
Paris
Bombay
Sydney
Singapore

The resulting output should look like:

LA
London
Tokyo
Prague
Paris
Bombay
Sydney

Any inputs appreciated.
Thanks.

Try:

awk 'NR>a+b{print A[NR%b]} {A[NR%b]=$0}' a=2 b=1 file
1 Like

Thanks for the solution. It works as long as the a and b doesnt equal to 0. It is possible that we may not have to delete any top and bottom records and in that case the value for top and bottom rows will be 0.

So, try:

awk 'NR>a+b{print (b>0 ? A[NR%b] : $0)} b>0{A[NR%b]=$0}' a=2 b=1 file
1 Like

Thanks it works great.

With bash there is no need for any external command:

#!/bin/bash
file=$1

mapfile -t xx < "$file"
n=${#xx[@]}
printf "%s\n" "${xx[@]:1:n-2}"
3 Likes

Nice! To remove the top lines as well as requested, try

top=2
bot=1
printf "%s\n" "${xx[@]:$top:n-$top-$bot}"
LA
London
Tokyo
Prague
Paris
Bombay
Sydney

Notes:

  • mapfile works well in recent versions of bash 4
  • The offset and length fields in ${parameter:offset:length} expansions are arithmetic expressions, and therefore do not need a dollar sign, so this should work too:
printf "%s\n" "${xx[@]:top:n-top-bot}"