Mohammad
Mohammad

Reputation: 1666

head command to skip last few lines of file on MAC OSX

I want to output all lines of a file, but skip last 4, on Terminal.

As per UNIX man page following could be a solution.

head -n -4 main.m

MAN Page:

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

I read man page here. http://unixhelp.ed.ac.uk/CGI/man-cgi?head

But on MAC OSx I get following error.

head: illegal line count -- -4

What else can be done to achieve this goal?

Upvotes: 19

Views: 14206

Answers (3)

Nobu
Nobu

Reputation: 10445

GNU version of head supports negative numbers.

brew install coreutils
ghead -n -4 main.m

Upvotes: 18

btanaka
btanaka

Reputation: 382

A Python one-liner:

$ cat foo
line 1
line 2
line 3
line 4
line 5
line 6
$ python -c "import sys; a=[]; [a.append(line) for line in sys.stdin]; [sys.stdout.write(l) for l in a[:-4]]" < foo
line 1
line 2

Upvotes: 3

pynexj
pynexj

Reputation: 20768

Use awk for example:

$ cat file
line 1
line 2
line 3
line 4
line 5
line 6
$ awk 'n>=4 { print a[n%4] } { a[n%4]=$0; n=n+1 }' file
line 1
line 2
$

It can be simplified to awk 'n>=4 { print a[n%4] } { a[n++%4]=$0 }' but I'm not sure if all awk implementations support it.

Upvotes: 4

Related Questions