sed Hold Space: h, H, g, G, x Basics
sed keeps a second buffer called the hold space, and h, H, g, G, and x move text between it and the pattern space.
Most edits live in the pattern space, the current line. The hold space is a scratch buffer that lets sed remember lines across iterations for reversing, joining, and tac-like tricks.
What it does
The pattern space holds the current line; the hold space is a separate buffer that persists between lines. h and H copy or append the pattern space into the hold space, g and G copy or append it back, and x swaps the two buffers.
Common usage
# reverse the order of lines (like tac)
sed -n '1!G; h; $p' file
# print each line preceded by the previous line
sed -n 'H; x; s/\n/ | /; p' file
# swap pattern and hold space
sed 'x' fileOptions
| Command | What it does |
|---|---|
| h | Copy pattern space into hold space (overwrite) |
| H | Append pattern space to hold space after a newline |
| g | Copy hold space into pattern space (overwrite) |
| G | Append hold space to pattern space after a newline |
| x | Exchange the pattern and hold spaces |
| n / N | Read the next line into (or onto) the pattern space |
In CI
Hold-space programs are powerful but hard to read; for anything beyond a small trick, awk or a real script is usually clearer and easier to maintain in a pipeline. The hold-space commands themselves are portable between GNU and BSD sed.
Common errors in CI
The hold space starts empty, so a leading G on the first line inserts a blank line; guard it with an address like 1!G. Forgetting -n in a print-based program doubles output because auto-print still runs alongside any p you added.