Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 748
rshah Avatar asked Nov 30 '17 14:11

rshah


People also ask

Which command will be used to delete N number of lines?

Sed Command to Delete Lines – Based on Position in File In the following examples, the sed command removes the lines in file that are in a particular position in a file. Here N indicates Nth line in a file.

How do you keep only the last n lines of a log file?

Use logrotate to do this automatically for you. there would be some exception case might come like no free space available to store log archive file (logrotate) in the server. For that kind of situation we have to keep only latest logs and remove other old log entries.

Which is the right command to fetch last 5 lines from a file?

To look at the last few lines of a file, use the tail command. tail works the same way as head: type tail and the filename to see the last 10 lines of that file, or type tail -number filename to see the last number lines of the file. Try using tail to look at the last five lines of your .

How do I print the last N lines of a file in Linux?

Linux Tail Command SyntaxTail is a command which prints the last few number of lines (10 lines by default) of a certain file, then terminates. Example 1: By default “tail” prints the last 10 lines of a file, then exits.


2 Answers

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.

like image 168
CGA1123 Avatar answered Sep 28 '22 01:09

CGA1123


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.

like image 38
sjsam Avatar answered Sep 28 '22 01:09

sjsam