计算stdin中的单词和行数

use*_*605 1 unix linux bash pipeline pipe

如何使用STANDARD UNIX UTILITIES编写程序,该程序将一次从标准输入一个字符读取数据,并将结果输出到标准输出.我知道它的运行类似于本例中的C程序.有人告诉我,这可以在一行代码中完成,但从未完成过Unix管道编程,所以我只是很好奇.该程序的目的是从标准输入读取数据并计算一行中的行数和标准输出中的单词和行的总数

我想出了以下代码,但我不确定:

tr A-Z a-z < file | tr -sc a-z | sort uniq -c wc '\n'

关于我如何得到我想要的任何想法或建议?

Chr*_*our 10

您可以使用wc (字数)-w选项来计算一个文件或字-l的线条.

$ cat file.txt
this file has 5 words.

$ wc -w file.txt             # Print number of words in file.txt
5 file.txt

$ wc -l file.txt             # Print number of lines in file.txt
1 file.txt

$ wc file.txt                # No option, print line, words, chars in file.txt
 1  5 23 file.txt
Run Code Online (Sandbox Code Playgroud)

其他选择wc:

  -c, --bytes            print the byte counts
  -m, --chars            print the character counts
  -l, --lines            print the newline counts
  -L, --max-line-length  print the length of the longest line
Run Code Online (Sandbox Code Playgroud)

  • 您也可以使用以下命令从stdin中读取(不涉及文件):&lt;command_production_output&gt; | wc -l (3认同)
  • @ArthurEirich 是的,如果您不想要换行符 `echo -n foo |,请使用 `-n` wc -m` (2认同)