Bash 如何计算文件中给定单词的出现次数? 问题
此脚本检查不同文件中的不同单词。在不知道这个词之前,我如何计算它的出现 输出 输出应该是数值,如果它与给定文件中的搜索词匹配,则应使用无效输出进行回复Bash 如何计算文件中给定单词的出现次数? 问题,bash,shell,unix,Bash,Shell,Unix,此脚本检查不同文件中的不同单词。在不知道这个词之前,我如何计算它的出现 输出 输出应该是数值,如果它与给定文件中的搜索词匹配,则应使用无效输出进行回复 #!/bin/bash if [ "Hello" -ne 1 ] then echo "Pass appropriate number of command line arguments" else if [ -e "$1" ] then if [ -f "$1" ] then if [
#!/bin/bash
if [ "Hello" -ne 1 ]
then
echo "Pass appropriate number of command line arguments"
else
if [ -e "$1" ]
then
if [ -f "$1" ]
then
if [ -r "$1" ]
then
grep -wc "Hello" $1
else
echo "Input file does not have read permission"
fi
else
echo "Input file is not an ordinary file"
fi
else
echo "Input file does not exist"
fi
fi
< >在文件中计数一个字,可以考虑创建这样的文件
#!/bin/bash
#search_word.sh
cnt=$(grep "$1" "$2" -o | wc -l)
if [ "$cnt" -eq 0 ]
then
echo "This file has no word as $1"
else
echo "This file has $cnt times of the word $1"
fi
并根据需要从命令提示符中调用
$ . ./search_word.sh 'myword' myfile.txt
代表wc
字数
- 如果您想不区分大小写计数(例如,
或WORD
或WORD
被认为是相同的),然后替换前面的标记word
-o
与| wc-l
-io
- 如果您查找任何单词的精确匹配项(例如,在搜索
单词
的过程中,
不被计算在内),则在搜索之前替换标记WOR
-o
与| wc-l
-wio
如果[“你好”-ne 1]
没有意义<代码>“Hello”始终与1
不同,更糟糕的是“Hello”
不是整数,因此会导致错误。