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.
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.
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.
sed -ie '$d' filename.txt
The i
option tells sed
to edit the file in place.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With