0

What is this doing? What are these: !b, :a, :trail?

sed -i -e '/LIMOC_SECTION=SERVICENAME_FULSC/!b' -e ':a' \
    -e "s/^PRIMARY_IP=.*/PRIMARY_IP=${primaryip}/;t trail" \
    -e 'n;ba' -e ':trail' -e 'n;btrail' $ssocfg
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
karthi
  • 21

1 Answers1

2

Rewritten:

# If a line does not match "LIMOC_SECTION=SERVICENAME_FULSC", jump to end
# (leave untouched)
/LIMOC_SECTION=SERVICENAME_FULSC/! b

# Label "a"
:a

# Substitute everything on the right side of "=" with the contents of $primaryip
s/^PRIMARY_IP=.*/PRIMARY_IP=${primaryip}/

# If there was a substitution on the current line, jump to label "trail"
t trail

# Print pattern space and read next line
n

# Jump to label "a"
b a

# Label "trail"
:trail

# Print pattern space and read next line
n

# Jump to label "trail"
b trail

What this effectively does is substituting $primaryip on the right-hand side of the line starting with PRIMARY_IP=, but only for the first occurrence after the line matching LIMOC_SECTION=SERVICENAME_FULSC.

It's a combination of how to replace only the first occurrence in a file with replacing only within a limited range.

As for the individual commands and options used:

  • The -i option is for in-place editing.
  • The -e options mark individual parts of the sed script.
  • :label is a mark in a sed program that can be jumped to using the b or t branching commands.
  • b is unconditional branching. If used without a label, it branches to the end of all commands, i.e., just prints the pattern space. If used with a label, it jumps to that label.
  • t is conditional branching: the branching only happens if there was a successful substitution since the last line was read or since the last branching command.
  • n reads the next line into pattern space and prints the current one (unless auto-printing is suppressed; not the case here).
  • s is the substitution command.

I'd say the command could be simplified, though:

sed -i '/LIMOC_SECTION=SERVICENAME_FULSC/,$ {
    1,/^PRIMARY_IP=.*/ s/^\(PRIMARY_IP=\).*/\1'"$primaryip"'/
}' "$ssocfg"

does the same. It takes the range of lines from the one matching LIMOC_SECTION to the end of the file, and within that range, it performs the substitution on the first line that matches PRIMARY_IP.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116