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

标签 linux bash text sed grep

我有一个挑战。我有这段文字:

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

我想知道“特征”和“退出”之间的“值”一词出现了多少次。所以,我希望是这样的:

3
2
2
1
2

我尝试使用 sedgrep 但我无法得到 sed 给我返回 nth ' -n -e "/^characteristic/,/^exit/p"'。我确信 bash 可以在没有很多do while/doneif 的情况下做到这一点。

感谢您的帮助。

最佳答案

我会说:

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

非常简单:

$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

关于linux - 计算文件中 2 个字符串之间匹配的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50573665/

相关文章:

linux -/etc/vsftpd/_vsftpd.conf : binary operator expected on Red Hat

php - 如何使用 php 代码从 linux 中的/tmp 文件夹取消链接临时文件

java - 如何编写 shell 脚本来获取给定的进程空闲时间?

bash - 将 stderr 重定向到使用进程替换创建的子 shell 时出现问题

text - UITextView周围的边框

javascript - 禁止滚动文本

linux - 在 AIX/bash 上以 bash 循环读取文件比在 Linux/ksh 中慢得多 - BLOCKSIZE?

c++ - Qt Assistant 在 Linux 中因启用远程控制选项而失败

linux - 如果内容包含字符串,则在两个定界符之间打印文本 block

python - 使用 Python/NLTK 提取一组单词,然后将其与标准英语词典进行比较