Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 如何计算文件中给定单词的出现次数? 问题_Bash_Shell_Unix - Fatal编程技术网

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

你的问题是什么?有一个类似这样的问题,比如5个问题:
如果[“你好”-ne 1]
没有意义<代码>“Hello”
始终与
1
不同,更糟糕的是
“Hello”
不是整数,因此会导致错误。