I am just wondering what is the b
command for sed
in Linux. For example:
sed "/some pattern/b" a.txt
I am just wondering what is the b
command for sed
in Linux. For example:
sed "/some pattern/b" a.txt
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.
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.