I don't understand what x does when it comes to exchanging the contents of hold and pattern buffer. Does it exchange the data between hold and pattern so that any previous data in hold or pattern is deleted? what happens exactly?
1 Answer
Probably the best way to explain those is translate to a more verbose language like perl
. In sed
, the hold space is like a static variable that is initialised with an empty line, and the pattern space a variable which sed
assigns in turn to every line of input. Something like:
$hold_space = "\n";
LINE: while ($pattern_space = <>) {
<sed commands go here>
print $pattern_space; # unless -n option is passed
}
x
swaps pattern and hold space, and it just does that.
($pattern_space, $hold_space) = ($hold_space, $pattern_space);
Now, the hold space contains what the pattern space contained (the current input line unless any other command modified it). And the pattern space is replaced with whatever the hold space contained, so will be output at the end before processing the next line of input (where the pattern space will be assigned the new input line).
The pattern space is what you work on. So you need the data in there if you want to do anything with it. The hold space is a storing area which can be used if you need to keep data between the processing of two lines of input.
g
gets the hold space into the pattern space, but then you lose the original pattern space. x
, preserves the old pattern space in the hold space. So for instance, to edit the hold space, you can do x;s/.../.../;x
to do some substitution on the hold space.
-
I still don't understand exactly. I have a text file with 10 numbers, with 1 number per line. When I do,
sed -n ':loop H;!b loop;x;$p' nums.txt
,then why is it that I only the last 2 numbers gets printed. Whereas, if I useg
, it will print the complete list?– daparicOct 22, 2018 at 18:38 -
This
sed
thing is devious. I get it now. Correct is:sed -n ':loop H;!b loop;${x;p}' nums.txt
. That is, I have toconstrained
myx
to only operate at the end.– daparicOct 22, 2018 at 18:43