3

I am just wondering what is the b command for sed in Linux. For example:

sed "/some pattern/b" a.txt  
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user5679799
  • 31
  • 1
  • 2

2 Answers2

2

The b command stands for branching: unconditionally branch to label. The label may be omitted (as in your example), in which case the next cycle is started.

Note that in most cases, use of this command means that you are probably better off programming in some real programming language like awk, Perl or Python.

Claudio
  • 10,614
  • 4
  • 31
  • 71
  • I find when the label is omitted it allows you to `think positive` about your data. By which I mean by positively bypassing lines it allows you to focus on those that remain. It can also obviate the need to group `{..}` commands. – potong Dec 15 '15 at 08:05
1

In POSIX sed and GNU sed — and other variants of sed — the b command jumps to a label in the script, or in the absence of a label name, to the end of the script. It is an unconditional jump. There's a conditional jump too; that's t. And you make a label with :label.

In the context of the script in your question, the b is useless. If the pattern matches, it goes to the end of the script, just as it does if there is no match.

For an example of when the t command is useful, consider the data file (data):

Be very, very, very, very, very, very scared of sed scripts with branches.

Now consider the outputs of these sed scripts:

$ sed 's/very, very/very/' data
Be very, very, very, very, very scared of sed scripts with branches.
$ sed 's/very, very/very/g' data
Be very, very, very scared of sed scripts with branches.
$ sed -e ':label' -e 's/very, very/very/g' -e 't label' data
Be very scared of sed scripts with branches.
$

Make sure you understand what the s///g modifier does and why the result is as it is.

I went poking around my $HOME/bin directory and found 97 scripts in it that use sed, including some very convoluted chunks of sed. I only found one script (rmemptysubdirs) that uses sed labels and branching:

# Remove empty directories from paths

find "$@" -type d -print |
sed -ne 'p
:b
s%/[^/]*$%%
p
t b' |
sort -ur |
xargs rmdir 2>/dev/null

The sed script here converts a line containing:

/absolute/path/name/for/directory

into:

/absolute/path/name/for/directory
/absolute/path/name/for
/absolute/path/name
/absolute/path
/absolute

Note that the script uses a label b, not the b command.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    Might want to note that GNU will branch to an empty label instead of the end of the script if `b` is used without a label name. – 123 Dec 15 '15 at 10:43
  • @123: I don't see the behaviour you claim documented in the GNU `sed` documentation on [branching](https://www.gnu.org/software/sed/manual/sed.html#Programming-Commands). – Jonathan Leffler Dec 15 '15 at 13:44