Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I learn the sed branches in Linux

Tags:

linux

sed

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.

like image 447
user175386049 Avatar asked Sep 20 '25 10:09

user175386049


2 Answers

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".

like image 187
tripleee Avatar answered Sep 23 '25 00:09

tripleee


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?
  • How to remove characters from a word if they are also in the next word?
  • sed: hold pattern and rearrange line?
  • How to replace all the blanks within square brackets with an underscore using sed?

And I'm sure there are a lot of others.

like image 41
Jonathan Leffler Avatar answered Sep 23 '25 01:09

Jonathan Leffler