如何计算文件中字符串的出现次数? [英] How can I count the occurrences of a string within a file?

查看:103
本文介绍了如何计算文件中字符串的出现次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅以此代码为例.假设它是HTML/文本文件,如果我想知道echo出现的总次数,该如何使用bash进行处理?

Just take this code as an example. Pretending it is an HTML/text file, if I would like to know the total number of times that echo appears, how can I do it using bash?

new_user()
{
    echo "Preparing to add a new user..."
    sleep 2
    adduser     # run the adduser program
}

echo "1. Add user"
echo "2. Exit"

echo "Enter your choice: "
read choice


case $choice in
    1) new_user     # call the new_user() function
       ;;
    *) exit
       ;;
esac 

推荐答案

这将输出包含您的搜索字符串的的数量.

This will output the number of lines that contain your search string.

grep -c "echo" FILE

但是,这不会计算文件中的出现次数(即,如果您在一行上多次回显).

This won't, however, count the number of occurrences in the file (ie, if you have echo multiple times on one line).

经过一番摸索,您可以使用下面这些肮脏的代码来获取出现的次数:

After playing around a bit, you could get the number of occurrences using this dirty little bit of code:

sed 's/echo/echo\n/g' FILE | grep -c "echo"

这基本上在每个echo实例之后添加一个换行符,因此它们每个都在自己的行上,从而使grep可以对这些行进行计数.例如,如果您只想要单词"echo"而不是"echoing",则可以优化正则表达式.

This basically adds a newline following every instance of echo so they're each on their own line, allowing grep to count those lines. You can refine the regex if you only want the word "echo", as opposed to "echoing", for example.

这篇关于如何计算文件中字符串的出现次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆