bash - 脚本中每一行的字数

标签 bash

我必须编写一个脚本来使用 while 循环读取每一行并计算每一行中的单词数。到目前为止,我可以获得总行数和每行的文本。我在使用 wc -w 命令计算每行的字数并显示它时遇到问题。当我把它和 printf 语句放在同一行时,它给出了一个不准确的计数。我必须将文本 block 通过管道传输到脚本,以便它计算单词数,例如: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 

最佳答案

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

 awk '$0="line"NR": "NF' imagine.txt

关于bash - 脚本中每一行的字数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9106881/

相关文章:

regex - 使用 sed 在附加文本之前追加两个新行

linux - 为什么 [ -n $var ] 在空字符串上为真?

bash - 如何在 PS1 中设置条件换行符?

linux - 如何将字符串作为可选字符串在 expect 脚本中等待它?

linux - 在 windows 操作系统上运行用 linux 编写的 Shell 脚本

node.js - Node 脚本如何在我当前的 bash 上下文(进程)中运行?

bash重装后找不到ghc?

linux - bash 将输出重定向到文件,但结果不完整

Bash脚本上传文件到hdfs

linux - 是否可以将 tr 与文件中的内容一起使用?