1

How can I delete the last line of a file without reading the entire file or rewriting it in any temp file? I tried to use sed but it reads the entire file into memory which is not feasible.

I want to remove the blank line from the end and save the change to the same file.

Since the file is very big and reading through the complete file would be slow, I am looking for a better way.

Prashant Kumar
  • 2,057
  • 2
  • 9
  • 22

3 Answers3

1

simple sed command to delete last line:

sed '$d' <file>

here in sed $ is the last line.

You can try awk command:

awk 'NR > 1{print t} {t = $0}END{if (NF) print }' file

Using cat:

cat file.txt | head -n -1 > new_file.txt
danglingpointer
  • 4,708
  • 3
  • 24
  • 42
0

The easiest way I can think of is:

sed -i '${/^$/d}' filename

edited to delete only blank end line.

Your only option not using sed that won't read the entire file is to stat the file to get the size and then use dd to skip to the end before you start reading. However, telling sed to only operate on the last line, does essentially that.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
0

Take a look at

Remove the last line from a file in Bash

Edit: I tested

dd if=/dev/null of=<filename> bs=1 seek=$(echo $(stat --format=%s <filename> ) - $( tail -n1 <filename> | wc -c) | bc )

and it does what you want

Community
  • 1
  • 1
rinn2883
  • 366
  • 1
  • 14