Multiline Processing

N — append next line to pattern space
cat <<'EOF' > /tmp/multi-n.txt
first
second
third
fourth
EOF
# N pulls next line into pattern space separated by \n — prints pairs
sed 'N;s/\n/ | /' /tmp/multi-n.txt
P — print first line of multi-line pattern space
cat <<'EOF' > /tmp/multi-p.txt
alpha
beta
gamma
delta
EOF
# N loads two lines; P prints only the first; D deletes first and restarts cycle
sed -n 'N;P' /tmp/multi-p.txt
D — delete first line of pattern space and restart
cat <<'EOF' > /tmp/multi-d.txt
AAA
BBB
CCC
DDD
EOF
# Sliding window: N appends next; P prints first; D removes first and loops
sed 'N;P;D' /tmp/multi-d.txt
Join every two lines into one
cat <<'EOF' > /tmp/join-pairs.txt
key: name
value: alice
key: role
value: admin
key: level
value: senior
EOF
sed 'N;s/\n/ | /' /tmp/join-pairs.txt
Join continuation lines (backslash-newline)
cat <<'EOF' > /tmp/continuation.txt
CFLAGS=-O2 \
  -Wall \
  -Werror
LDFLAGS=-lm
CC=gcc \
  -std=c11
EOF
# If line ends with \, append next line and remove backslash-newline; loop
sed ':a;/\\$/{N;s/\\\n/ /;ba}' /tmp/continuation.txt
Remove blank lines after section headers
cat <<'EOF' > /tmp/blank-after.txt
== Introduction

This is content.

== Methods

More content here.
EOF
# When line starts with ==, pull next; if next is blank, remove it
sed '/^==/{N;s/\n$//}' /tmp/blank-after.txt
Process paragraph-at-a-time — join until blank line
cat <<'EOF' > /tmp/paragraphs.txt
This is paragraph one
which spans multiple
lines of text.

This is paragraph two
also multi-line.

Single line paragraph.
EOF
# Accumulate non-blank lines; on blank line or EOF, process paragraph
sed -n '/^$/{x;s/\n/ /g;/./p;d};H;${x;s/\n/ /g;/./p}' /tmp/paragraphs.txt
Search and replace across line boundaries
cat <<'EOF' > /tmp/cross-line.txt
the quick
brown fox
jumps over
the lazy dog
EOF
# Load entire file into pattern space, then replace across the newline boundary
sed ':a;N;$!ba;s/quick\nbrown/fast\nred/' /tmp/cross-line.txt
Print lines surrounding a match (poor man’s grep -A1 -B1)
cat <<'EOF' > /tmp/surround.txt
line 1
line 2
TARGET
line 4
line 5
EOF
# N creates 3-line sliding window; check middle for TARGET; P prints context
sed -n 'N;N;/\nTARGET\n/{p;d};P;D' /tmp/surround.txt
Slurp entire file then operate — load all lines first
cat <<'EOF' > /tmp/slurp.txt
start
middle one
middle two
end
EOF
# :a;N;$!ba loads entire file; then global replace works across all lines
sed ':a;N;$!ba;s/middle/MIDDLE/g' /tmp/slurp.txt