【问题标题】:Count number of words in file, bash script计算文件中的单词数,bash脚本
【发布时间】:2014-02-03 21:11:21
【问题描述】:

如何在 bash 脚本中打印指定文件中的字数。例如,它将作为

运行
cat test | ./bash_script.sh

cat test

Hello World
This is a test

运行cat test | ./bash_script 的输出看起来像

Word count: 6. 

我知道它可以在没有脚本的情况下完成。我正在尝试将wc -w 实现到一个 bash 脚本中,该脚本将计算如上所示的单词。任何帮助表示赞赏!谢谢你

【问题讨论】:

标签: linux bash


【解决方案1】:

如果给定一个输入流,如图所示:

while read -a words; do (( num += ${#words[@]} )); done
echo Word count: $num.

从@FredrikPihl 在评论中给出的链接扩展:这从作为参数给出的每个文件中读取,如果没有给出文件,则从标准输入中读取:

for f in "${@:-/dev/stdin}"; do
    while read -a words; do (( num += ${#words[@]} )); done < "$f"
done
echo Word count: $num.

这应该更快:

for f in "${@:-/dev/stdin}"; do
    words=( $(< "$f") )
    (( num += ${#words[@]} ))
done
echo Word count: $num.

【讨论】:

    【解决方案2】:

    在纯 bash 中:

    read -a arr -d $'\004'
    echo ${#arr[@]}
    

    【讨论】:

      【解决方案3】:
      #!/bin/bash
      word_count=$(wc -w)
      echo "Word count: $word_count."
      

      正如@keshlam 在 cmets 中指出的那样,这可以通过在 shell 脚本中执行 wc -w 轻松完成,我不明白它的用例是什么。

      尽管如此,上面的 shell 脚本将根据您的要求工作。下面是一个测试输出。

      【讨论】:

        【解决方案4】:

        我相信您需要的是可以添加到 bashrc 中的函数:

        function script1() {  wc -w $1; }
        
        script1 README.md 
        335 README.md
        

        您可以将函数添加到您的 .bash_rc 文件并在下一个控制台上调用它,或者如果您获取 .bashrc 文件,那么它将加载到函数中......从那时起,您可以像您一样调用函数名称查看文件,它会给你计数

        【讨论】:

          【解决方案5】:

          您可以将文件的内容扩展为参数,并在脚本中回显参数的数量。

          $# 扩展为脚本参数的数量

          #!/bin/bash
          
          echo "Word count: $#."
          

          然后执行:

          ./bash_script.sh $(cat file)

          【讨论】:

            【解决方案6】:

            试试这个:
            wc -w *.md | grep total | awk '{print $1}'

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-04-07
              • 1970-01-01
              • 1970-01-01
              • 2015-07-13
              • 1970-01-01
              • 2014-11-04
              相关资源
              最近更新 更多