简体   繁体   English

输出ls | wc -l

[英]Output of ls | wc -l

Normally the output of wc -l command gives the number of lines in a file. 通常, wc -l命令的输出给出文件中的行数。 But, when we pipe the output of ls command to it, it seems to show the number of files and directories and links in the current working directory correctly. 但是,当我们将ls命令的输出传递给它时,它似乎正确地显示了当前工作目录中的文件和目录以及链接的数量。

My question is that the output of the ls command displays names of some files and directory in the same line. 我的问题是ls命令的输出显示同一行中某些文件和目录的名称。 So, why in this case using ls | wc -l 那么,为什么在这种情况下使用ls | wc -l ls | wc -l gives the same output, as compared to ls -l | wc -l ls -l | wc -l相比, ls | wc -l给出相同的输出 ls -l | wc -l . ls -l | wc -l Thanks in advance. 提前致谢。

ls detects that it's being piped to another program instead of to the console, and outputs one file/directory per line. ls检测到它被传送到另一个程序而不是控制台,并且每行输出一个文件/目录。 You can try ls | cat 你可以尝试ls | cat ls | cat to see this behavior. ls | cat看到这种行为。

A program can check whether a file descriptor refers to a terminal or not and present different outputs depending on this. 程序可以检查文件描述符是否引用终端,并根据此提供不同的输出。 Check out isatty(3) which can be used for this purpose. 检查isatty(3)可用于此目的。

In fact it is common practice to simplify the output when it is piped to make further processing easier for other programs it might be piped into. 实际上,通常的做法是在管道输出时简化输出,以便进一步处理可能被管道传输的其他程序。 Especially the non-printable characters like terminal control codes which change colors, etc. could be a pain to process and are usually unnecessary when a user does not directly see the output. 尤其是诸如改变颜色等的终端控制代码之类的不可打印字符可能是难以处理的,并且当用户不直接看到输出时通常是不必要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM