Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I dont understand what x does when it comes to exchanging the contents of hold and pattern buffer.Does it exchanges the data between hold and pattern so that any previous data in hold or pattern is deleted.what happens exactly.

share|improve this question
    
You may want to check the edited answer to your other question. –  Stéphane Chazelas Mar 27 '13 at 12:16

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.