Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can we remove last 7 lines of file in unix [duplicate]

Tags:

shell

unix

sed

awk

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.

like image 306
Pooja25 Avatar asked Aug 25 '14 08:08

Pooja25


People also ask

How do I remove duplicate lines in files?

Remove duplicate lines with uniq If you don't need to preserve the order of the lines in the file, using the sort and uniq commands will do what you need in a very straightforward way. The sort command sorts the lines in alphanumeric order. The uniq command ensures that sequential identical lines are reduced to one.

How files with duplicate lines are handled in Unix?

The uniq command in UNIX is a command line utility for reporting or filtering repeated lines in a file. It can remove duplicates, show a count of occurrences, show only repeated lines, ignore certain characters and compare on specific fields.


2 Answers

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
like image 156
Kent Avatar answered Oct 06 '22 21:10

Kent


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.

like image 32
Jotne Avatar answered Oct 06 '22 21:10

Jotne