sed one Liner option -e

Hi,

I have the following command.(Delete all trailing blank lines at the end of a file.)

sed -e :a -e '/^\n*$/{$d;N;ba' -e '}'

I don't understand the logic of this command and also I don't understand why -e is used.
Can you please let me know the logic of this command and why three -e are used

Famous Sed One-Liners Explained, Part III: Selective Deletion of Certain Lines and Special Applications - good coders code, great reuse
here you can find the basic explanation for this command which i am not able to understand (82nd question)

Thank You

Hi,
This command does nothing because no line begin with "\n" when sed read a line.

Regards.

This command is actually removing blank lines from the end of my file.I have tested it.Its true that this line is not reading any \n from the file and appeding to the pattern space, but N in this command is causing \n to be appended to the pattern space. I am not sure how this command is removing all blank lines from the end of file..:confused::confused:

That one liner actually does what it is said to do. The -e s are not needed (at least in my linux mawk). Try printing the pattern space with the l command to see how it proceeds. If it finds only zero or more <NL> (\n) chars in the pattern space which is one or more empty lines, it apends the next line. If that is empty as well, repeat. If it's the last line, quit. Any other line, print the ensemble:

sed 'l; :a /^\n*$/{$d;N;l;ba}' file
foo$
foo
$
\n$
\n\nbar$


bar
baz$
baz
$
\n$
\n\n$
\n\n\n$
\n\n\n\n$
1 Like

I understood the logic..its was a great debugging tip to get the content of Pattern space. That was a new learning for me . But for some reason this command was not working in HP-UX without -e

Thank you..

I think this needs to be slightly modified: If it's the last line, delete the pattern space, print that (empty space) and quit.