【问题标题】:Single-line bash command that will count and display the occurrences of a particular string in a file [duplicate]单行 bash 命令,将计算并显示文件中特定字符串的出现次数[重复]
【发布时间】:2018-06-17 16:24:10
【问题描述】:

我是 Bash 和终端新手。我的任务是使用单行 Bash 终端命令计算特定区号的条目数。您能否为我指明实现这一目标的正确方向?我一直在使用bash scripting cheat sheet,但我对 bash 命令还不够熟悉,无法创建一个脚本来迭代并计算 [213] 在文件中出现的次数:

【问题讨论】:

  • 您希望像213 and second 213 这样的行被计为一次点击(大多数答案)还是两次点击(@jeremysprofile 的答案)?

标签: bash command-line terminal


【解决方案1】:

如果您在文件中的任何位置查找字符串123,则:

grep -c 123 file # counts 123 4123 41235 etc

如果你正在寻找“单词”123,那么:

grep -wc 123 file # counts 123 /123/ #123# etc., but not 1234 4123 ...

如果您希望单独计算同一行上出现的多个单词,请使用-o 选项:

grep -ow 123 file | wc -l

另见:

【讨论】:

    【解决方案2】:

    grep -o '213' 文件名 | wc -l

    以后,您应该尝试搜索命令的通用 形式。你会发现numberofsimilarquestions

    【讨论】:

      【解决方案3】:

      man grepgrep 有一个 count 选项。

      所以你想运行grep -c 213 file

      【讨论】:

        【解决方案4】:

        关注awk 在这里也可能对您有所帮助。(它将在 Input_file 的行中的任何位置查找字符串 213

        awk /213/{count++} END{print count}' Input_file
        

        如果您只想查找恰好具有数字 213 的行,请使用以下代码。

        awk /^213$/{count++} END{print count}' Input_file
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-05-24
          • 2020-06-14
          • 2020-05-03
          • 2011-07-08
          • 2012-05-31
          • 2011-05-03
          相关资源
          最近更新 更多