Sed, awk.grep - add a line to the end of the config section if the line doesn't already exist

I want to edit a file using sed / awk. The file consists of several configuration sections, for example:

SECTION 1 BEGIN
some stuff
SECTION END

SECTION 2 BEGIN
some stuff
some more stuff
important line
SECTION END

      

I want to add important line

to the end SECTION 2

if it doesn't already exist, preferably as a command one liner. I have looked into fgrep / sed combo in this question , but I am not quite clear on how to adapt it to what I need.

Note: Sections may contain blank lines.

Many thanks.

0


source to share


2 answers


Usage awk

:



awk '
  $0 == "SECTION 2 BEGIN" { inSec2 = 1 } 
  inSec2 && $0 == "important line" { hasImportant = 1 } 
  inSec2 && $0 == "SECTION END" { 
    if (!hasImportant) { print "important line" } 
    inSec2 = 0
  }
  1'

      

+5


source


Based on Michael's solution, there is a one-liner:

awk -vline="important line" '/^SECTION 2 BEGIN$/{f=1}f&&$0==line{f=0}f&&/^SECTION END$/{print line;f=0}1'<<EOT
SECTION 1 BEGIN
some stuff
SECTION END

SECTION 2 BEGIN
some stuff
some more stuff
SECTION END

SECTION 2 BEGIN
some stuff
some more stuff
important line
SECTION END

SECTION 3 BEGIN
oops
SECTION END
EOT

      



Output:

SECTION 1 BEGIN
some stuff
SECTION END

SECTION 2 BEGIN
some stuff
some more stuff
important line
SECTION END

SECTION 2 BEGIN
some stuff
some more stuff
important line
SECTION END

SECTION 3 BEGIN
oops
SECTION END

      

+3


source







All Articles