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.
From the sed one-liners:
Seems to be what you are looing for.
This might work for you (GNU sed):
You can get the total count of lines with
wc -l <file>
and usehead -n <total lines - lines to remove> <file>
Use
sed
, but let the shell do the math, with the goal being to use thed
command by giving a range (to remove the last 23 lines):To remove the last 3 lines, from inside out:
Gives the number of lines of the file: say 2196
We want to remove the last 23 lines, so for left side or range:
Gives: 2174 Thus the original sed after shell interpretation is:
With
-i
doing inplace edit, file is now 2173 lines!I came up with this, where n is the number of lines you want to delete:
It's a little roundabout, but I think it's easy to follow.
It can be done in 3 steps:
a) Count the number of lines in the file you want to edit:
b) Subtract from that number the number of lines to delete:
c) Tell sed to delete from that line number (
$x
) to the end: