I am trying but could able to understand the branches in sed.
Why do we need it and what purpose does it solve?
Example in this solution of removing the \n from the file, he uses:
sed ':a;N;$!ba;s/\n/ /g'
I am not able to understand the labels.
It's a simple goto. You need to declare a destination label with :label or just b without a label to the end of the script. There are also the conditional jumps t and T.
In your exanple script, the "address" condition $! is true for all lines except the last ($ means end of file, and ! negates the condition). Thus there is a loop which reads the entire file into the pattern space, then falls through to the action after the loop, which substitutes all (internal) newlines (in some dialects of sed).
# declare label 'a'
:a
# append next input line to pattern space
N
# loop back to 'a' unless at end of file
$!ba
# substitute all newlines in pattern space
s/\n/ /g
# fall through to end: print the pattern space
I would agree that "branch" is a slightly misleading term but it has a long history; a better term might be "jump" or "go to".
There are quite a lot of questions about sed where branches appear in the answer, including:
sed replace globally a delimiter with the first part of the line?sed: hold pattern and rearrange line?sed?And I'm sure there are a lot of others.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With