Hold Buffer Commands

h — copy pattern space to hold space
cat <<'EOF' > /tmp/hold-demo.txt
first
second
third
EOF
# h copies current line to hold; g retrieves it — prints "third" for every line
sed 'h;$!d;g' /tmp/hold-demo.txt
H — append pattern space to hold space (newline-separated)
cat <<'EOF' > /tmp/append-hold.txt
alpha
beta
gamma
EOF
# H appends each line to hold; at EOF, get hold and print — accumulates all lines
sed -n 'H;${g;p}' /tmp/append-hold.txt
g — overwrite pattern space with hold space
cat <<'EOF' > /tmp/get-hold.txt
HEADER
data line 1
data line 2
data line 3
EOF
# Save first line to hold; on other lines, overwrite pattern with hold — repeats HEADER
sed '1{h;d}; g' /tmp/get-hold.txt
G — append hold space to pattern space
cat <<'EOF' > /tmp/append-pattern.txt
one
two
three
EOF
# G appends hold (initially empty) — double-spaces the file
sed 'G' /tmp/append-pattern.txt
x — exchange pattern and hold space
cat <<'EOF' > /tmp/exchange.txt
AAA
BBB
CCC
DDD
EOF
# x swaps pattern/hold — prints previous line (hold starts empty, so first output is blank)
sed 'x' /tmp/exchange.txt
Reverse file line order using hold buffer
cat <<'EOF' > /tmp/reverse.txt
line 1
line 2
line 3
line 4
line 5
EOF
# Classic tac replacement: prepend each line to hold, print at EOF
sed -n '1!G;h;$p' /tmp/reverse.txt
Duplicate every line — print original then copy from hold
cat <<'EOF' > /tmp/duplicate.txt
alpha
beta
gamma
EOF
# h saves line; p prints it; g retrieves from hold — prints each line twice
sed 'h;p;g' /tmp/duplicate.txt
Print each line with the line before it (context via hold)
cat <<'EOF' > /tmp/context.txt
== Section A
content A1
content A2
== Section B
content B1
EOF
# x swaps: prints previous line; on match, get current back and print both
sed -n 'x;/./p;${x;p}' /tmp/context.txt
Swap adjacent lines — exchange pairs
cat <<'EOF' > /tmp/swap-pairs.txt
key1
value1
key2
value2
key3
value3
EOF
# For odd lines: hold. For even lines: get hold, append, print swapped.
sed -n 'h;n;G;p' /tmp/swap-pairs.txt
Collect lines between markers then emit as single line
cat <<'EOF' > /tmp/collect.txt
-- START --
item one
item two
item three
-- END --
other stuff
EOF
# Accumulate lines between START/END into hold, join with commas at END
sed -n '/START/,/END/{/START/d;/END/{x;s/\n/, /g;s/^, //;p;d};H}' /tmp/collect.txt