rshah
rshah

Reputation: 691

Copying last n lines to a new file and then removing the n lines from original

So I have a file where I want to move the last 3000 lines to another different file, and then create a new file from the original without the last 3000 lines.

I'm using a Mac and the command I used is as follows:

tail -n 3000 fer2017-testing-reduced.arff >> fer2017-training-reduced-3000-more-instances.arff; head -n -3000 fer2017-testing-reduced.arff > fer2017-testing-reduced-3000-less-instances.arff

However when I run this, I get the error:

head: illegal line count -- -3000

I'm not sure where I've gone wrong, or if this may be a mac issue?

Upvotes: 5

Views: 3215

Answers (3)

sjsam
sjsam

Reputation: 21965

If other tools are allowed, perhaps go for sed

sed -n '3000,${p}' file > filenew # print lines 3000 to end to new file
sed -i '3000,${d}' file # Use inplace edit to delete lines 3000 to end from orig.

The advantage here is that the $ auto matches the last line.

Upvotes: 3

CGA1123
CGA1123

Reputation: 132

Not all versions of head support negative line counts. The default installed on macOS doesn't.

If you have coreutils installed (If you have Homebrew installed you can do this: brew install coreutils) you should be able to use ghead -n -3000.

Upvotes: 5

Inian
Inian

Reputation: 85825

Read more info from why POSIX head and tail not feature equivalent, the POSIX version of head does not accept negative integers for the -n option.

Qutoting from the POSIX head command documentation,

-n number The first number lines of each input file shall be copied to standard output. The application shall ensure that the number option-argument is a positive decimal integer.

You are better changing head -n -3000 to tail -n +3001 to start from line 3000 to end of the file. Or use GNU supported head command which on Mac is available as part of GNU coreutils.

Upvotes: 2

Related Questions