I'm trying to come up with a sed
script to take all lines containing a pattern and move them to the end of the output. This is an exercise in learning hold vs pattern space and I'm struggling to come up with it (though I feel close).
I'm here:
$ echo -e "hi\nfoo1\nbar\nsomething\nfoo2\nyo" | sed -E '/foo/H; //d; $G'
hi
bar
something
yo
foo1
foo2
But I want the output to be:
hi
bar
something
yo
foo1
foo2
I understand why this is happening. It is because the first time we find foo
the hold space is empty so the H appends \n
to the blank hold space and then the first foo, which I suppose is fine. But then the $G does it again, namely another append which appends \n
plus what is in the hold space to the pattern space.
I tried a final delete command with /^$/d
but that didn't remove the blank line (I think this is because this pattern is being matched not against the last line, but against the, now, multiline pattern space which has a \n\n
in it.
I'm sure the sed
gurus have a fix for me.