简体   繁体   English

计算文件中2个字符串之间匹配的行数

[英]Count number of lines that matches between 2 strings from file

I have a challenge. 我有挑战 I have this text: 我有这段文字:

characteristic "type"
   value "A"
   value "B"
   value "C" 
   default-value "B" 
exit 
characteristic "active"
   value "no"
   value "yes"
   default-value "no" 
exit
characteristic "traffic"
   value "disabled" 
   value "enabled"
   default-value "enabled"
exit
characteristic "quota" 
   value "enabled"
   default-value "disabled"
exit
characteristic "redirect"
   value "disabled"
   value "enabled"
   default-value "disabled"
exit

I want to know how many times is word 'value' between 'characteristic' and 'exit'. 我想知道“特征”和“退出”之间的“价值”一词有多少次。 So, I hope something like this: 所以,我希望是这样的:

3
2
2
1
2

I tried to used sed and grep but I cannot get sed give me back nth ocurrence of '-n -e "/^characteristic/,/^exit/ p"'. 我尝试使用sedgrep,但是我无法通过sed将'-n -e“ / ^ characteristic /,/ ^^ exit / p”'的第n次回传给我。 I'm sure bash can do it without a lot of do while/done and if . 我敢肯定, bash无需大量的while / doneif就能做到。

I appreciate your help. 我感谢您的帮助。

I'd say: 我会说:

awk '$1 == "characteristic" { ctr = 0 } $1 == "exit" { print ctr } $1 == "value" { ++ctr }' filename

Very simply: 很简单:

$1 == "characteristic" { ctr = 0 }  # Start of a new section: reset counter
$1 == "exit" { print ctr }          # end of section: print counter
$1 == "value" { ++ctr }             # value line: increase counter

I decided to try to solve this with GNU sed's e command. 我决定尝试使用GNU sed的e命令解决此问题。

This allows those familiar with sed to inline shell commands to do things like count words. 这使熟悉sed的人员可以内联Shell命令来执行诸如计数单词之类的操作。

The idea was to condense each section to one line, and pass it to grep -ow value | wc -l 想法是将每一节压缩为一行,然后将其传递给grep -ow value | wc -l grep -ow value | wc -l to count the occurrences of the word "value." grep -ow value | wc -l计算单词“值”的出现次数。

Command: sed -f char.sed input-file 命令: sed -f char.sed input-file

Where the char.sed command file for sed is: sed的char.sed命令文件位于:

:a
/exit/{
  s/\n/ /g
  s/-/b/g
  s/^/echo /
  s/$/ | grep -ow value | wc -l/
  e
  n
}
N
ba

What that does is N on each line until /exit/ at which point newlines are replaced with spaces, dashes are replaced with b (so that "default-value" doesn't match grep -w value ). 所做的是在每行上保留N ,直到/exit/为止,此时换行符用空格替换,破折号用b替换(这样,“默认值”与grep -w value不匹配)。 Then the entire line is prefaced with echo and suffixed with | grep -ow value | wc -l 然后,整行以echo开头,并以| grep -ow value | wc -l后缀 | grep -ow value | wc -l | grep -ow value | wc -l . | grep -ow value | wc -l The e command is then used to execute the command as constructed and stick the output of the command in the output stream. 然后,使用e命令执行所构造的命令,并将命令的输出粘贴在输出流中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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