1

How can I delete the last line of a file without reading the entire file or rewriting it in any temp file. I dont want to use sed as it reads the entire file into memory. There is a blank line at last. I want to remove that and save the change to that file only so that the file does not contain blank line at last.

Prashant Kumar
  • 1,770
  • 2
  • 7
  • 20

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,388
  • 3
  • 22
  • 40
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
  • 75,900
  • 6
  • 54
  • 79
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
  • 336
  • 1
  • 12