I want to remove some n lines from the end of a file. Can this be done using sed?
For example, to remove lines from 2 to 4, I can use
$ sed '2,4d' file
But I don't know the line numbers. I can delete the last line using
$sed $d file
but I want to know the way to remove n lines from the end. Please let me know how to do that using sed or some other method.
This will remove the last 12 lines
You could use head for this.
Use
$ head --lines=-N file > new_file
where N is the number of lines you want to remove from the file.
The contents of the original file minus the last N lines are now in new_file
Just for completeness I would like to add my solution. I ended up doing this with the standard
ed
:This deletes the last 2 lines using in-place editing (although it does use a temporary file in
/tmp
!!)To truncate very large files truly in-place we have
truncate
command. It doesn't know about lines, buttail
+wc
can convert lines to bytes:There is an obvious race condition if the file is written at the same time. In this case it may be better to use
head
- it counts bytes from the beginning of file (mind disk IO), so we will always truncate on line boundary (possibly more lines than expected if file is actively written):Handy one-liner if you fail login attempt putting password in place of username:
If hardcoding n is an option, you can use sequential calls to sed. For instance, to delete the last three lines, delete the last one line thrice:
This will remove the last 3 lines from
file
:for i in $(seq 1 3); do sed -i '$d' file; done;