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
  • Both examples do not inf-loop, despite never starting a new cycle.
  • In the first example, the n commands first prints the content of the pattern space, empties the pattern space then reads the next input line.
  • In the second example, the N commands appends the next input line to the pattern space (with a newline). Lines are accumulated in the pattern space until there are no more input lines to read, then the N command terminates the sed program. When the program terminates, the end-of-cycle actions are performed, and the entire pattern space is printed.
  • The second example requires GNU sed, because it uses the non-POSIX-standard behavior of N. See the “N command on the last line” paragraph in Reporting Bugs.
  • To further examine the difference between the two examples, try the following commands:
    printf '%s\n' aa bb cc dd | sed ':x ; n ; = ; bx'
    printf '%s\n' aa bb cc dd | sed ':x ; N ; = ; bx'
    printf '%s\n' aa bb cc dd | sed ':x ; n ; s/\n/***/ ; bx'
    printf '%s\n' aa bb cc dd | sed ':x ; N ; s/\n/***/ ; bx'