简体   繁体   English

计算文件中的单词数,bash 脚本

[英]Count number of words in file, bash script

How could i go printing the number of words in a specified file in a bash script.我怎么能在 bash 脚本中打印指定文件中的单词数。 For example it will be run as例如,它将作为

cat test | ./bash_script.sh

cat test

Hello World
This is a test

Output of running cat test | ./bash_script运行cat test | ./bash_script输出cat test | ./bash_script cat test | ./bash_script would look like cat test | ./bash_script看起来像

Word count: 6. 

I am aware that it can be done without a script.我知道它可以在没有脚本的情况下完成。 I am trying to implement wc -w into a bash script that will count the words like shown above.我正在尝试将wc -w实现到一个 bash 脚本中,该脚本将计算如上所示的单词。 Any help is appreciated!任何帮助表示赞赏! Thank You谢谢你

if given a stream of input as shown:如果给出一个输入流,如图所示:

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

Extending from the link @FredrikPihl gave in a comment: this reads from each file given as an argument or from stdin if no files given:从@FredrikPihl 在评论中给出的链接扩展:这从作为参数给出的每个文件中读取,如果没有给出文件,则从 stdin 中读取:

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

this should be faster:这应该更快:

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

in pure bash:在纯 bash 中:

read -a arr -d $'\004'
echo ${#arr[@]}
#!/bin/bash
word_count=$(wc -w)
echo "Word count: $word_count."

As pointed by @keshlam in the comments, this can be easily done by executing wc -w from the shell script, I didn't understand what could be its use case.正如@keshlam 在评论中指出的那样,这可以通过从 shell 脚本执行wc -w轻松完成,我不明白它的用例是什么。

Although, the above shell script will work as per your requirement.虽然,上面的 shell 脚本将根据您的要求工作。 Below is a test output.下面是一个测试输出。

在此处输入图片说明

I believe what you need is a function that you could add to your bashrc:我相信您需要的是一个可以添加到 bashrc 的函数:

function script1() {  wc -w $1; }

script1 README.md 
335 README.md

You can add the function to your .bash_rc file and call it what you want upon next console or if you source your .bashrc file then it will load in the function ... from then on you can call function name like you see with file and it will give you count您可以将该函数添加到您的 .bash_rc 文件中,并在下一个控制台上调用它,或者如果您提供 .bashrc 文件,那么它将加载到函数中......从那时起您可以调用函数名称,就像您在文件中看到的一样它会给你数

You could expand the contents of the file as arguments and echo the number of arguments in the script.您可以将文件的内容扩展为参数并在脚本中回显参数的数量。

$# Expands to the number of script arguments $#扩展到脚本参数的数量

#!/bin/bash

echo "Word count: $#."

Then execute:然后执行:

./bash_script.sh $(cat file)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM