5
votes

How to remove last 7 lines from the csv file using unix commands.

For example -

abc
bffkms
slds
Row started 1
Row started 2
Row started 3
Row started 4
Row started 5
Row started 6
Row started 7

I want to delete the last 7 lines from above file. Please suggest.

2

2 Answers

12
votes

You can use head

head -n-7 file

from man page:

 -n, --lines=[-]K
              print the first K lines instead of the first 10;
              with the leading '-', print all but the last K lines of each file

like:

kent$ seq 10|head -n-7
1
2
3
1
votes

An tac awk combination.

tac | awk  'NR>7' | tac

eks:

seq 1 10 | tac | awk  'NR>7' | tac
1
2
3

Another awk version

awk 'FNR==NR {a++;next} FNR<a-7 ' file{,}

This reads the file twice {,}, first counts line, second prints all but last 7 lines.