简体   繁体   中英

awk print only lines between two patterns removing first match

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM