Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: remove all lines of input except last n lines

Tags:

bash

sed

awk

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.

like image 858
rupat Avatar asked Nov 14 '13 12:11

rupat


People also ask

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.

How will you select all lines of a file except the last line in Unix?

head -n -1 will give you all except the last line of its input. Save this answer.

How do you remove the last 3 lines in Unix?

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.

How do I get the last n lines of a file in Linux?

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.


1 Answers

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.

like image 63
Ivaylo Strandjev Avatar answered Nov 15 '22 23:11

Ivaylo Strandjev