我怎么能算一个字符串使用bash一个文件中出现? [英] How can I count the occurrences of a string within a file using bash?
问题描述
只是借此code作为一个例子。 pretending它是一个HTML /文本文件,如果我想知道的次数总数回声
出现,我该怎么办呢使用bash?
new_user()
{
回声preparing添加一个新用户。
睡眠2
#的adduser运行该程序的adduser
}回声1.添加用户
回声2.退出回声请输入您的选择:
选择读
案例$选择在
1)new_user#调用new_user()函数
;;
*) 出口
;;
ESAC
这将输出的行的包含搜索字符串。数
的grep -cecho文件
这也不会,不过,计数出现的次数在文件中(也就是说,如果你在一个线路回声多次)。
编辑:
张望了一下打后,您可以用code的这个肮脏的点点获得出现的次数:
SED的/回声/回音\\ n / g的文件| grep的-c回声
这主要增加了以下回声的每个实例所以他们各自对自己的行换行,让grep来计算这些行。您可以细化正则表达式,如果你只想要的单词回声,而不是呼应,例如。
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).
edit:
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"
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.
这篇关于我怎么能算一个字符串使用bash一个文件中出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!