3

I would like to remove a curly braces {} block + its "name" (2 word prefix), if a pattern is found inside the block.
I tried some sed magic but couldn't get it.
For example:

  • Pattern: PATTERN PATTERN-X

Input

m m1 {  
    s s1;  
    s s2;  
    c c1 {  
        s s3;   
        c c2 {  
            PATTERN PATTERN-X  
            ...  
        }  
        s s4;
    }  
    c c3 {  
        PATTERN PATTERN-X  
        ...
        c c4 {
            s s4;
        }
    }  
}

Output

m m1 {  
    s s1;  
    s s2;  
    c c1 {  
        s s3;   
        s s4;
    }  
}
  • Is that a generalized nagios config file? – Jeff Schaller Dec 29 '17 at 19:33
  • I don't know what nagios is. That's a schema .yang file – hudac Dec 29 '17 at 19:55
1

You can try this awk

awk '
$0~/{/{
  if(b) {
    print b
  b=""
  }
  if(c)
    c++
}
$0~/PATTERN/ {
  b=""
  c=2
}
$0~/}/ {
  if(c)
    c--
}
!c {
  if(b)
    b=b RS
  b=b $0
}
END {
  print b
}
' infile
  • Unfortunately I have an example this solution doesn't work for. I can't post it in comments becuase the file won't be seen well – hudac Jan 1 '18 at 8:05
  • If curly bracket always open and close, we can do something. – ctac_ Jan 1 '18 at 12:47
  • @hudac you're not supposed to post updates in comments. Please edit your question instead, so we all get to see the pathological example. – roaima Jan 1 '18 at 12:59
  • Sorry, I was wrong. It works on that example also. – hudac Jan 1 '18 at 14:29
  • @ctac_ why does c=2 in $0~/PATTERN/ {, and not 1 ? – hudac Jan 2 '18 at 20:19
1

Usually it is not good idea to parse any functional language and this example looks like that. Parsing tools were designed to deal with human language where regular expression works fine. With that being said... we still can try.

Here is my approach using pcregrep:

pcregrep -Mv '.*{.*\n.*PATTERN(([^{}]|\n)*|([^{}]|\n)*{([^{}]|\n)*}.*([^{}]|\n)*)}.*' file

Works fine with your example, i.e. zero or one block {} depth after PATTERN. If you have more than one block just extend this to suit your needs.

Output:

m m1 {  
    s s1;  
    s s2;  
    c c1 {  
        s s3;   
    }  
}
  • "If you have more than one block just extend this to suit your needs." - In the general case I have N-depth blocks – hudac Jan 1 '18 at 8:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.