6.4.1 Branching and Cycles

The b,t and T commands can be followed by a label (typically a single letter). Labels are defined with a colon followed by one or more letters (e.g. ‘:x’). If the label is omitted the branch commands restart the cycle. Note the difference between branching to a label and restarting the cycle: when a cycle is restarted, sed first prints the current content of the pattern space, then reads the next input line into the pattern space; Jumping to a label (even if it is at the beginning of the program) does not print the pattern space and does not read the next input line.

The following program is a no-op. The b command (the only command in the program) does not have a label, and thus simply restarts the cycle. On each cycle, the pattern space is printed and the next input line is read:

$ seq 3 | sed b
1
2
3

The following example is an infinite-loop - it doesn’t terminate and doesn’t print anything. The b command jumps to the ‘x’ label, and a new cycle is never started:

$ seq 3 | sed ':x ; bx'

# The above command requires gnu sed (which supports additional
# commands following a label, without a newline). A portable equivalent:
#     sed -e ':x' -e bx

Branching is often complemented with the n or N commands: both commands read the next input line into the pattern space without waiting for the cycle to restart. Before reading the next input line, n prints the current pattern space then empties it, while N appends a newline and the next input line to the pattern space.

Consider the following two examples:

$ seq 3 | sed ':x ; n ; bx'
1
2
3

$ seq 3 | sed ':x ; N ; bx'
1
2
3