bash – 脚本中每行的字数

我必须编写一个脚本来使用while循环读取每一行并计算每行中的单词数.到目前为止,我可以在自己的行上获得每行的总行数和文本.我无法使用wc -w命令计算每行的字数并显示它.当我把它放在同一行,因为printf语句给出了一个不准确的计数.我必须将文本块传递给脚本,以便对单词进行计数,例如:cat file.txt | word_count.sh

有什么建议?

码:

#!/bin/bash
line_num=1

while read line;do
  printf "line $line_num: $line"
  ((line_num++))
done

结果:

cat imagine.txt | word_counts.sh 
line1: magine there's no countries 
line2: It isn't hard to do 
line3: nothing to kill or die for 
line4: And no religion too 
line5: Imagine all the people living life in peace
printf "$line_num: $(echo $line | wc -w)"

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...