bash 计算标准输入中的单词和行数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13691834/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:55:30  来源:igfitidea点击:

count number of words and lines from stdin

linuxbashunixpipepipeline

提问by user1832605

How can i write a program using STANDARD UNIX UTILITIES that will read data from standard input one character at a time and out the results to standard output. I know that it runs similar to what a C program in this case. I was told that this could be done in one line of code but never done Unix Pipeline Programming so i am just curious. The purpose of the program is to read data from standard input and count the number of words an lines and out in standard output the total number of words and lines

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

I came up with the following code but i am unsure:

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

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

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

Any thoughts or suggestions on how i can get what i want?

关于如何获得我想要的东西的任何想法或建议?

回答by Chris Seymour

You use wc(word count)with the -woption to count words in a file or -lfor lines.

您可以使用wc(word count)-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

Other options to wc:

其他选项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