Coder Perfect

How to erase the final n lines of a file with sed

Problem

I’d like to cut n lines off the end of a file. Is it possible to achieve this with sed?

To eliminate lines 2 to 4, for example, I can use

$ sed '2,4d' file

However, I am unfamiliar with the line numbers. I can get rid of the last line by using

$sed $d file

However, I’d like to know how to eliminate n lines from the end. Please show me how to achieve this with sed or another approach.

Asked by mezda

Solution #1

I’m not sure about sed, but it’s possible with head:

head -n -2 myfile.txt

Answered by ams

Solution #2

You can use sequential calls to sed if hardcoding n isn’t a possibility. To erase the last three lines, for example, delete the last one line three times:

sed '$d' file | sed '$d' | sed '$d'

Answered by Kyle

Solution #3

The following are some of the sed one-liners:

# delete the last 10 lines of a file
sed -e :a -e '$d;N;2,10ba' -e 'P;D'   # method 1
sed -n -e :a -e '1,10!{P;N;D;};N;ba'  # method 2

That appears to be what you’re looking for.

Answered by qstebom

Solution #4

A funny & simple sed and tac solution :

n=4
tac file.txt | sed "1,$n{d}" | tac

NOTE

Answered by Gilles Quenot

Solution #5

Use sed, but leave the math to the shell, with the purpose of using the d command with a range (to get rid of the last 23 lines):

sed -i "$(($(wc -l < file)-22)),\$d" file

From the inside out, remove the last three lines:

$(wc -l < file)

Gives the number of lines of the file: say 2196

We want to remove the last 23 lines, so for left side or range:

$((2196-22))

Result: 2174 As a result, the original sed after shell interpretation is as follows:

sed -i '2174,$d' file

The file is now 2173 lines long, thanks to -i’s inplace edit!

If you wish to save it as a new file, use the following code:

sed -i '2174,$d' file > outputfile

Answered by lzc

Post is based on https://stackoverflow.com/questions/13380607/how-to-use-sed-to-remove-the-last-n-lines-of-a-file