Arun
Arun

Reputation: 135

Delete second-to-last line of file using sed

I have a file.txt and I have to delete the second-to-last line of the file. The below three sed commands are able to print the second-to-last line. But I need to delete that line. Any help??

sed -e '$!{h;d;}' -e x file.txt

sed -n 'x;$p' file.txt

sed 'x;$!d' file.txt

$ cat file.txt
apple
pears
banana
carrot
berry

Can we delete the second-to-last line of a file:
a. not based on any string/pattern.
b. based on a pattern - if second-to-last line contains "carrot"

Upvotes: 3

Views: 5316

Answers (2)

potong
potong

Reputation: 58400

This might work for you (GNU sed):

sed -i 'N;$!P;D' file

This sets up a window of two lines in the pattern space and then prints the first of those whenever the second is not the last. The last line is always printed because the next line can not be fetched.

Deleting the second-to-last line of a file based on a pattern can be achieved with:

sed -i 'N;$!P;${/pattern.*\n/!P};D'

Upvotes: 5

rsuarez
rsuarez

Reputation: 179

I know this is an old question, but as I've not seen what I use, I'll add it in case it helps.

Combining sed with tac makes this very easy:

mv file.txt file.txt.bak
tac file.txt.bak | sed '2d' | tac > file.txt

This would remove the second-to-last line of the file. It's not a "pure" sed solution, and it needs an intermediate file, but I use it often because IMHO it's easier to understand.

Upvotes: 5

Related Questions