使用sed计算字符串出现的次数? [英] Count the number of occurrences of a string using sed?
问题描述
我有一个文件,其中包含多次写入的标题".如果title"是一行中的第一个字符串,如何使用 sed 命令找到title"在该文件中写入的次数?例如
I have a file which contains "title" written in it many times. How can I find the number of times "title" is written in that file using the sed command provided that "title" is the first string in a line? e.g.
# title
title
title
应该输出 count = 2 因为在第一行标题不是第一个字符串.
should output the count = 2 because in first line title is not the first string.
更新
我使用 awk 找到总出现次数为:
I used awk to find the total number of occurrences as:
awk '$1 ~ /title/ {++c} END {print c}' FS=: myFile.txt
但是我怎样才能告诉 awk 只计算那些具有 title 第一个字符串的行,如上面示例中所述?
But how can I tell awk to count only those lines having title the first string as explained in example above?
推荐答案
我认为 sed
不合适,除非你在管道中使用它来转换你的文件需要出现在单独的行中,然后使用 grep -c
计算出现次数.
I don't think sed
would be appropriate, unless you use it in a pipeline to convert your file so that the word you need appears on separate lines, and then use grep -c
to count the occurrences.
我喜欢 Jonathan 使用 tr
将空格转换为换行符的想法.这种方法的美妙之处在于连续的空格被转换为多个空行但没关系因为 grep
将能够只计算包含单个单词 ' 的行数标题'.
I like Jonathan's idea of using tr
to convert spaces to newlines. The beauty of this method is that successive spaces get converted to multiple blank lines but it doesn't matter because grep
will be able to count just the lines with the single word 'title'.
这篇关于使用sed计算字符串出现的次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!