bash 脚本中每一行的字数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9106881/
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
word count of each line in a script
提问by Jason Gagnon
I have to write a script to read each line using a while loop and count the number of words in each line. So far i can get the total number of lines and the text for each on its own line. I am having trouble using the wc -w command to count the number of words for each line and display it. when i put it on the same line as the printf statement is gives an inaccurate count. I have to pipe the text tile to the script so it will count the words, for example: cat file.txt | word_count.sh
我必须编写一个脚本来使用 while 循环读取每一行并计算每行中的单词数。到目前为止,我可以获得总行数和每个行的文本。我在使用 wc -w 命令计算每行的单词数并显示它时遇到了问题。当我把它和 printf 语句放在同一行时,它给出了一个不准确的计数。我必须将文本图块通过管道传输到脚本,以便它计算字数,例如: cat file.txt | word_count.sh
any suggestions?
有什么建议?
code:
代码:
#!/bin/bash
line_num=1
while read line;do
printf "line $line_num: $line"
((line_num++))
done
results:
结果:
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
采纳答案by John Zwinck
printf "$line_num: $(echo $line | wc -w)"
回答by SiegeX
In case you want to impress at the risk of getting caught for plagiarism:
如果您想冒着因抄袭被抓到的风险而给人留下深刻印象:
awk '##代码##="line"NR": "NF' imagine.txt

