Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting last line of a file

Tags:

linux

shell

I want to delete last line of a file on a particular condition. I used sed and cut but they work only on the output stream but I want to do this in the file. Can someone help me? Thanks in advance.

like image 568
Shweta Avatar asked Mar 03 '11 05:03

Shweta


People also ask

How do I remove lines from a file?

Sed Command to Delete Lines – Based on Position in File In the following examples, the sed command removes the lines in file that are in a particular position in a file. Here N indicates Nth line in a file. In the following example, the sed command removes the first line in a file.

How do you remove the last line of a file in Java?

If you wanted to delete the last line from the file without creating a new file, you could do something like this: RandomAccessFile f = new RandomAccessFile(fileName, "rw"); long length = f. length() - 1; do { length -= 1; f.


2 Answers

sed -ie '$d' filename.txt

The i option tells sed to edit the file in place.

like image 121
Shad Avatar answered Oct 26 '22 05:10

Shad


I'll use a variant on another answer and suggest a simple use of ed:

ed tmp.tmp << EOC
$
d
w
q
EOC

Otherwise you can use sed/cut to a temporary file and mv to overwrite the starting file.

like image 33
darklion Avatar answered Oct 26 '22 04:10

darklion