且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用sed计算字符串出现的次数?

更新时间:2021-08-10 10:17:12

我认为 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'.