Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does deleting sed pattern space with 'd' erase hold space as well?

Tags:

sed

Can someone please explain why this is happening?

This is expected:

$ echo -e "foo\nbar" | sed -n 'h; x; p'
foo
bar

I put every line in the hold space, then swap hold space and pattern space, then print the pattern space, so every line is printed. Now, why is the following different?

$ echo -e "foo\nbar" | sed -n 'h; d; x; p'

I thought that wouldn't be, because I delete the pattern space before swapping, so the stored line should be put back to the pattern space anyway. It's the hold space that should be empty after x;, right? I delete the pattern space, then swap. Where does the line I've saved go?

like image 344
Lev Levitsky Avatar asked Jan 17 '23 16:01

Lev Levitsky


2 Answers

When you use d, the pattern space is cleared, the next line is read, and processing starts over from the beginning of the script. Thus, you never actually reach the x and p steps, instead just copying to the hold space and deleting.

like image 63
Michael J. Barber Avatar answered Jan 19 '23 06:01

Michael J. Barber


I guess it's related to the following line in man sed:

d Delete pattern space. Start next cycle.

The following works as expected:

$ echo -e "foo\nbar" | sed -n 'h; s/.*//; g; p'
foo
bar

Sorry for bothering you guys.

like image 36
Lev Levitsky Avatar answered Jan 19 '23 05:01

Lev Levitsky