Frage

From some program, I get output of the form

aaaaa
bbbbb

ccccc
ddddd
eeeee
fffff

ggggg
hhhhh
iiiii

including the final blank line.

I want to get only the last lines of each block, i.e. every line followed by a blank line:

bbbbb
fffff
iiiii

I tried with sed and checked (as usual) the sed1liners, but could not come up with something useful.

War es hilfreich?

Lösung

You have to play with the hold space.

sed -ne '/^$/ { g; p; b }; h; $ { g; p }' infile

How does it work?

For each normal line, copy it to hold space (h) overwritting previous content. And for special cases (empty lines and last line of file), take the content of hold space and print it.

It yields:

bbbbb
fffff
iiiii

Andere Tipps

with awk:

awk '
    /^[[:blank:]]*$/ {print prev} 
    {prev=$0}
    END {if (length(prev)) print prev}
'

With awk:

$ awk '!$0{print a} {a=$0}' file
bbbbb
fffff
  • !$0{print a} if the line is empty, print the stored line a.
  • {a=$0} store the line in the variable a.

This might work for you (GNU sed):

sed '$!N;/.\n$/P;D' file
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top