I want to remove all lines except n last or first n lines with a short one-liner.
Example:
---
aaaa
bbbb
cccc
dddd
cat/echo/find ... | sed < all except last 2 lines >
should result
aaaa
bbbb
---
aaaa
bbbb
cccc
dddd
eeee
ffff
cat/echo/find ... | sed < all except last 2 lines >
should result
aaaa
bbbb
cccc
dddd
---
I need this also for a very high n. So it could possible to set n=100 or so.
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.
head -n -1 will give you all except the last line of its input. Save this answer.
Using the wc and sed Commands However, our problem is to delete the last three lines from the input file. Since our input file has ten lines, the sed command: sed '8,$ d' input. txt will be the solution to the problem.
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.
To remove the last 2 lines you can use something like this:
head -n $(($(wc -l < "$filename") - 2)) "$filename"
Not very elegant but it should work. I use wc -l to count the number of lines and then I use head to only display the first number of lines minus 2 lines.
EDIT: to keep only last N
lines you could do
tail -n $N $filename
To keep only first N
lines you could do.
head -n $N $filename
It seems I may have misunderstood your question and that is why I add these two commands.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With