Deleting the lines in the file from the end of a file perl
In general if you want to delete lines from a file based on range of lines from the begining.we can do as below:for eg:
>cat file
1
2
3
4
5
6
7
8
9
>
now if i want to print lines from 4th to 6th i do below:
tail +4 file|head -3
logic behind this is:
tail +(4th line) file|head -(6-4+1)
suppose if you want to delte the lines from 4th to 6th then:
awk 'NR<4 || NR>6' file
Suppose if we want to delete last 5 lines in a file use below:
tail -r temp | nawk 'NR>5'|tail -r
Now the tricky thing is what if i want to delete the lines from the last i.e., the last 4th line till the last 6th line.
Below is the logic:
perl -lne 'push(@a,$_);if(eof){splice @a,$.-6,6-4+1;print join "\n",@a}' file
Logic behind this is :
perl -lne 'push(@a,$_);if(eof){splice @a,$.-(last sixth line),(last sixth line number which is 6)-(last 4th line number which is 4)+1;print join "\n",@a}' file
0 comments: