脚本中每行的字数

Jas*_*non 6 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
Run Code Online (Sandbox Code Playgroud)

结果:

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 
Run Code Online (Sandbox Code Playgroud)

Sie*_*geX 7

如果你想冒着被剽窃的风险留下深刻印象:

 awk '$0="line"NR": "NF' imagine.txt
Run Code Online (Sandbox Code Playgroud)


Joh*_*nck 4

printf "$line_num: $(echo $line | wc -w)"
Run Code Online (Sandbox Code Playgroud)