Strip 3 header lines and 4 trailer lines

Hello friends,

I want to remove 3 header lines and 4 trailer lines,

I am using following , is it correct ?


sed '1,3d';'4,$ d' filename 
sed '1,3 d' f | sed -e :a -e '$d;N;2,4ba' -e 'P;D'

Thanks anbu

Anbu23 can you please explain the code

sed '1,3 d' f | sed -e :a -e '$d;N;2,4ba' -e 'P;D'

I am confused.

sed -e :a -e '$d;N;2,4ba' -e 'P;D'

$d;N;2,4ba
N appends second line to pattern space. Since second line is in pattern space 2,4ba makes control to shift to -e :a.
Then N appends third line to pattern space. 2,4ba makes control shift to -e :a.
Then N appends fourth line to pattern space and control is shifted to -e :a.
If the fourth line is the last line then $d deletes all the lines in the pattern space else N appends fifth line to pattern space.
Now 2,4ba is not satisfied then P is executed to print the first line in pattern space and this line is then deleted by D command.
Then control is shifted to start of commands. If fifth line is last line then $d deletes all the lines in the pattern space and continues to till the end of file.

Another one (using awk) ..
(( upper_lim = $(cat $1 | wc -l) - 4 ))
awk -v upp_lim=$upper_lim ' NR>3 && NR<=upp_lim {print $0}' $1

Is it correct? Run it and see.

To remove an arbitrary number of lines from both hte top and bottom of a file, use my topntail command:

b=
e=
while getopts b:e: opt
do
  case $opt in
      b) b=$OPTARG ;;
      e) e=$OPTARG ;;
  esac
done
shift $(( $OPTIND - 1 ))

case $b$e in
    *[!0-9]*) exit 5 ;;
esac

if [ ${e:-1} -eq 0 ]
then
  sed "1,${b:-1}d" "$@"
else
  awk 'NR > b + e { print buf[ NR % e ] }
                  { buf[ NR % e ] = $0 }' b=${b:-1} e=${e:-1} "$@"
fi

Another one in python....

file_handle = open('filename', "r")
line_list = file_handle.readlines()
strip_data = line_list[3:len(line_list)-4]
for each in strip_data: print each.lstrip().rstrip()
file_handle.close()

Remove the last four lines

sed -n -e :a -e "N;$ s/\(\n[^\n]*\)\{4\}$//p;ba" file

Another awk solution:

awk '{line[FNR]=$0} END{for(i=4;i<FNR-3;i++)print line}' file

Regards