Ferragam
Ferragam

Reputation: 55

Remove function from file using sed or awk

I want to remove the function engine "map" { ... "foobar" ... }.

I tried in so many ways, it's so hard because it has empty lines and '}' at the end, delimiters doesn't work

mainfunc {

  var = "baz"

  engine "map" {

    func {

      var0 = "foo"
      border = { 1, 1, 1, 1 }
      var1 = "bar"
    }
  }
}

mainfunc {

  var = "baz"

  engine "map" {

    func {

      var0 = "foo"
      border = { 1, 1, 1, 1 }
      var1 = "foobar"
    }
  }
}

... # more functions like 'mainfunc'

I tried

sed '/engine/,/^\s\s}$/d' file

but removes every engine function, I just need the one containing "foobar", maybe a pattern match everything even newlines until foobar something like this:

sed '/engine(.*)foobar/,/^\s\s}$/d' file

Is it possible?

Upvotes: 3

Views: 2056

Answers (2)

bian
bian

Reputation: 1456

Try:

sed '/engine/{:a;N;/foobar/{N;N;d};/  }/b;ba}' filename

or:

awk '/engine/{c=1}c{b=b?b"\n"$0:$0;if(/{/)a++;if(/}/)a--;if(!a){if(b!~/foobar/)print b;c=0;b="";next}}!c' filename

Upvotes: 3

Andreas Louv
Andreas Louv

Reputation: 47119

I would simple count the numbers of open / close brackets when you match engine "map", cannot say if this only works in gawk

awk '
  /^[ \t]*engine "map"/ {
    ship=1; # ship is used as a boolean
    b=0 # The factor between open / close brackets
  }
  ship {
    b += split($0, tmp, "{"); # Count numbers of { in line
    b -= split($0, tmp, "}"); # Count numbers of } in line
    # If open / close brackets are equal the function ends
    if(b==0) { 
      ship = 0;
    }
    # Ship the rest (printing)
    next;
  }
  1 # Print line
' file

Split returns the number of matches: split(string, array [, fieldsep [, seps ] ]):

Divide string into pieces defined by fieldpat and store the pieces in array and the separator strings in the seps array. The first piece is stored in array[1], the second piece in array[2], and so forth. The third argument, fieldpat, is a regexp describing the fields in string (just as FPAT is a regexp describing the fields in input records). It may be either a regexp constant or a string. If fieldpat is omitted, the value of FPAT is used. patsplit() returns the number of elements created.

Upvotes: 1

Related Questions