Delete first 6 lines and last two lines

hello all,

i have a text file and i want to remove the first 6 lines and last two lines of it

thanks for your help

What about searching these forums and adapting the solutions found?
Anyhow ... try this:

awk 'NR<=6 {next}
     {A[NR%3]=$0; j=(NR+1)%3; if (A[j]) print A[j]}
    ' file

thanks but i want easy way i have an idea in my mind to count the lines and use head and tail combination to get what i want but i need a very simple code one way using sed or awk ?

What could be simpler than the awk script proposed?

# cat file
line1
line2
line3
line4
line5
line6
line7
line8
line9
line10
line11
line12
line13
line14
line15
line16
line17
line18
line19
line20
line21
line22
# sed -e "1,6 d" -e 'N;$!P;$!D;$d' file
line7
line8
line9
line10
line11
line12
line13
line14
line15
line16
line17
line18
line19
line20

perfect solution thanks alot

could you explain it for me to be understand

sed -e "1,6 d" -e 'N;$!P;$!D;$d' file

what each symbol of these mean N;$!P;$!D;$d

thanks alot again

From the man of sed:

-e => add the script to the commands to be executed

1,6d => deletes a sequence of 1 to 6 lines. d stands for delete
N=> Read the next line in Pattern space
$!P=> If the current line is not the last line, print the current line
$!D=> If the current line is not the last line, delete the current line
$d=> If the current line is the last line, delete everything in the pattern-space

combination of all this "N;$!P;$!D;$d" will delete the last two lines

thanks alot can i change it for example to delete last 5 lines ??

nawk -v a=6 -v b=5 '{c[cnt++]=$0}END{for(i=a;i<NR-b;i++){print c}}' inputfile
a=counter from the top
b=counter from the bottom

Change these numbers a=6 , b=5 as you desire and you can remove lines from top to bottom as you wish.

# cat file
line1
line2
line3
line4
line5
line6
line7
line8
line9
line10
line11
line12
line13
line14
line15
line16
line17
line18
line19
line20
line21

You can replace 5 with 'n' on the number of lines you want to delete

# sed -n -e :a -e '1,5!{P;N;D;};N;ba' file
line1
line2
line3
line4
line5
line6
line7
line8
line9
line10
line11
line12
line13
line14
line15
line16
awk 'NR>x+y{print A[NR%y]} {A[NR%y]=$0}' x=6 y=2 infile
2 Likes

@Scrutinizer: Brilliant!

@Scrutinizer: Can you please explain A[NR%y]

Hi sathyaonnuix, A[NR%y] has the function of a rolling buffer, it contains a number of lines that is equal to y, which is the number of lines that should not be printed at the end of the input file.. After the last line, whatever is in the buffer ends up not being printed.

1 Like