3
votes

I would like get last non-blank line from a file using sed. I was able to achieve expected result using two pipelined sed:

$ echo -e "\n\none\n\ntwo\n\n\nthree\n\n" | sed '/^$/d' | sed -n '$p'
three

However, I wonder if is it possible to get that using just one sed command. Maybe by copying each non-blank line to the buffer one after another, overwriting previous content and printing the buffer at the end? I am not sure if it can be done in sed, it is just my guess.

Please don't propose me to use awk, tail, etc - I am interested just in sed. Thank you.

2

2 Answers

4
votes

Maybe :

sed -e '/^$/d' -e '$ !d'

?

Other way with hold buffer:

sed -e '/^$/ !h
        $ {x;p;}'
3
votes

This might work for you:

echo -e "\n\none\n\ntwo\n\n\nthree\n\n" |
sed '/^$/!h;$!d;g'
three