1

This one prints between the two patterns

printf "/n"| openssl s_client -showcerts -connect www.google.com:443 | awk '/-----BEGIN CERTIFICATE-----/,/-----END CERTIFICATE-----/'

Then this one removes the first matching set but then prints all the superfluous junk

printf "/n"| openssl s_client -showcerts -connect www.google.com:443 | awk '/-----BEGIN CERTIFICATE-----/{f=1;++c} !(f && c==2); /-----END CERTIFICATE-----/{f=0}'

I would like to get the second results with out the extra stuff outside the pattern matches I could by just using two awks.

printf "/n"| openssl s_client -showcerts -connect www.google.com:443 | awk '/-----BEGIN CERTIFICATE-----/,/-----END CERTIFICATE-----/' | awk '/-----BEGIN CERTIFICATE-----/{f=1;++c} !(f && c==2); /-----END CERTIFICATE-----/{f=0}'

But I wanted to do it in one if it is possible.

menders65
  • 43
  • 8

1 Answers1

1

That seems quite similar to this question, and I'd adapt my sed answer as follows:

sed -n '/-----BEGIN CERTIFICATE----/,/-----END CERTIFICATE-----/ { // { x; s/$/./; x; }; x; /.../ { x; p; x; }; x; }' filename

That is

/-----BEGIN CERTIFICATE----/,/-----END CERTIFICATE-----/ {
  // {           
    x
    s/$/./      #  keep a counter of boundary lines in the hold buffer
    x
  }
  x             # inspect the counter
  /.../ {       # if counter >= 3
    x
    p           # print the line
    x
  }
  x
}               # with -n, falling off the end here will not lead to printing.

Alternatively, the sanest awk I can think of is

awk '/----BEGIN CERTIFICATE----/ { flag = 1; ++ctr } flag && ctr >= 2 { print } /-----END CERTIFICATE-----/ { flag = 0 }' filename

more readably:

/----BEGIN CERTIFICATE----/ {  # beginning of a range:
  flag = 1                     # raise flag that we're in one
  ++ctr                        # count in which one
}
flag && ctr >= 2 { print }     # print only if in a range and not in the first
/-----END CERTIFICATE-----/ {  # when leaving
  flag = 0                     # lower flag
}
Wintermute
  • 42,983
  • 5
  • 77
  • 80