awk只打印两个模式之间的线,删除第一个匹配项 [英] 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}'
我想获得第二个结果,而无需使用两个awks就能获得的模式匹配之外的多余内容.
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
那是
/-----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.
或者,我能想到的最聪明的awk
Alternatively, the sanest awk I can think of is
awk '/----BEGIN CERTIFICATE----/ { flag = 1; ++ctr } flag && ctr >= 2 { print } /-----END CERTIFICATE-----/ { flag = 0 }' filename
更可读:
/----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
}
这篇关于awk只打印两个模式之间的线,删除第一个匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!