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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21537854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:27:08  来源:igfitidea点击:

Count number of words in file, bash script

linuxbash

提问by user2860658

How could i go printing the number of words in a specified file in a bash script. For example it will be run as

我怎么能在 bash 脚本中打印指定文件中的单词数。例如,它将作为

cat test | ./bash_script.sh

cat test

Hello World
This is a test

Output of running cat test | ./bash_scriptwould 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 -winto a bash script that will count the words like shown above. Any help is appreciated! Thank You

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

回答by glenn Hymanman

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.

回答by ALiX

in pure bash:

在纯 bash 中:

read -a arr -d $'
#!/bin/bash

echo "Word count: $#."
4' echo ${#arr[@]}

回答by John B

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

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

function script1() {  wc -w ; }

script1 README.md 
335 README.md

Then execute:

然后执行:

./bash_script.sh $(cat file)

./bash_script.sh $(cat file)

回答by Ben Hamilton

Try this:
wc -w *.md | grep total | awk '{print $1}'

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

回答by V H

I believe what you need is a function that you could add to your bashrc:

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

##代码##

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 文件,那么它将加载到函数中......从那时起,您可以像在文件中看到的那样调用函数名称它会给你数