shell脚本,用于查找文本文件中特定单词的出现次数

时间:2014-05-20 04:38:10

标签: unix

我的档案是ss.txt

Another instance started
Another instance started 
Another instance started
Another instance started
No instance started
No instance started
No instance started
No instance started

如果我使用shell脚本程序

#!/bin/sh
t=0
#temp=0
echo "Enter filename"
read f1
if [ -f $f1 ]
then
echo "1.count char,words,lines"
echo "2.particular word to find in file"
echo "3.exit"
echo "Enter ur choice?"
read ch
case $ch in
1) wc -c $f1
   echo "characters"
   wc -w $f1
   echo "words"
   wc -l $f1
   echo "lines" ;;
2) echo "Enter the word whose occurence has to be found"
   read c
   t='echo $f1 | wc -c'
   echo $t ;;
3) exit ;;
esac
else
echo "File does not exist"
fi

如果我运行此代码,我会得到以下输出 我可以得到选项2正确,即单词出现不正确

我喜欢

Enter filename
ss.txt
1.count char,words,lines
2.particular word in file
3.exit
Enter ur choice?
1
180 ss.txt
characters
24 ss.txt
words
8 ss.txt
lines

这是我得到的正确,但对于选择2我得到像

Enter filename
ss.txt
1.count char,words,lines
2.particular word in file
3.exit
Enter ur choice?
2
Enter the word whose occurence has to be found
Another
0

看到我在这里得零,但输出应为4

2 个答案:

答案 0 :(得分:0)

从:改变:

t='echo $f1 | wc -c'

t=`grep -o "$c" "${f1}"|wc -l`

答案 1 :(得分:0)

请根据您的要求尝试以下命令

t = grep -c "text" "${f1}"( - c, - 每个输入文件的匹配行的计数)
  或
t = grep -o "text" "${f1}"( - o,仅显示匹配PATTERN的匹配行的一部分。)

bcsmc2rtese001 [〜/ Shell_p] $ grep -c“另一个”ss.txt
4
bcsmc2rtese001 [〜/ Shell_p] $ grep -o“另一个”ss.txt
另一个
另一个
另一个
另一个