我正在尝试编写一个简单的bash脚本,它在其中接收一个文本文件,遍历文件并告诉我某个字符串出现在文件中的次数。我想最终将它用于自定义日志搜索器(例如,搜索特定日志文件中的“登录”等字样),但由于我对bash相对较新,因此遇到了一些困难。我希望能够根据自己的意愿快速搜索不同日志的不同日志,并查看它们出现的次数。一切都很完美,直到我的循环。我认为我使用grep是错误的,但我不确定这是否是问题。我的循环代码可能看起来有点奇怪,因为我已经使用了一段时间并且一直在调整事物。我已经做了很多搜索,但我觉得我是唯一一个遇到过这个问题的人(希望不是因为它非常简单,我只是吮吸)。非常感谢任何和所有的帮助,感谢所有人。
编辑:我想说明字符串的每个实例而不仅仅是 每行一个实例
#!/bin/bash
echo "This bash script counts the instances of a user-defined string in a file."
echo "Enter a file to search:"
read fileName
echo " "
echo $path
if [ -f "$fileName" ] || [ -d "$fileName" ]; then
echo "File Checker Complete: '$fileName' is a file."
echo " "
echo "Enter a string that you would like to count the occurances of in '$fileName'."
read stringChoice
echo " "
echo "You are looking for '$stringChoice'. Counting...."
#TRYING WITH A WHILE LOOP
count=0
cat $fileName | while read line
do
if echo $line | grep $stringChoice; then
count=$[ count + 1 ]
done
echo "Finished processing file"
#TRYING WITH A FOR LOOP
# count=0
# for i in $(cat $fileName); do
# echo $i
# if grep "$stringChoice"; then
# count=$[ $count + 1 ]
# echo $count
# fi
# done
if [ $count == 1 ] ; then
echo " "
echo "The string '$stringChoice' occurs $count time in '$fileName'."
elif [ $count > 1 ]; then
echo " "
echo "The string '$stringChoice' occurs $count times in '$fileName'."
fi
elif [ ! -f "$fileName" ]; then
echo "File does not exist, please enter the correct file name."
fi
答案 0 :(得分:3)
要查找和计算字符串的所有匹配项,您可以使用仅匹配单词而不是整行的grep -o
,并将结果传递给wc
read string; grep -o "$string" yourfile.txt | wc -l
答案 1 :(得分:0)
您在代码中犯了基本语法错误。此外,count的变量永远不会更新,因为while循环正在子shell中执行,因此更新的计数值永远不会反射回来。
请将您的代码更改为以下代码以获得所需的结果。
#!/bin/bash
echo "This bash script counts the instances of a user-defined string in a file."
echo "Enter a file to search:"
read fileName
echo " "
echo $path
if [ -f "$fileName" ] ; then
echo "File Checker Complete: '$fileName' is a file."
echo " "
echo "Enter a string that you would like to count the occurances of in '$fileName'."
read stringChoice
echo " "
echo "You are looking for '$stringChoice'. Counting...."
#TRYING WITH A WHILE LOOP
count=0
while read line
do
if echo $line | grep $stringChoice; then
count=`expr $count + 1`
fi
done < "$fileName"
echo "Finished processing file"
echo "The string '$stringChoice' occurs $count time in '$fileName'."
elif [ ! -f "$fileName" ]; then
echo "File does not exist, please enter the correct file name."
fi