GNU 'ls' command not outputing the same over a pipe [duplicate]

瘦欲@ 提交于 2019-12-11 11:39:23

问题


When I execute the command ls on my system, I get the following output:

System:~ user# ls
asd  goodfile  testfile  this is a test file

However, when I pipe ls to another program (such as cat or gawk), the following is output:

System:~ user# ls | cat
asd
goodfile
testfile
this is a test file

How do I get ls to read the terminal size and output the same over a pipe as it does when printing directly to the terminal?


This question has been solved.

Since I'm using bash, I used the following to achieve the desired output:

System:~ user# ls -C -w "$(tput cols)" | cat

回答1:


Use ls -C to get columnar output again.

When ls detects that its output isn't a terminal, it assumes that its output is being processed by some other process that wants to parse it, so it switches to -1 (one-entry-per-line) mode to make parsing easier. To make it format in columns as when it's outputting directly to a terminal, use -C to switch back to column mode.

(Note, you may also have to use --color if you care about color output, which is also normally suppressed by outputting to a pipe.)




回答2:


Maybe -x "list entries by lines instead of by columns" with possible -w "assume screen width instead of current value" is what you need.




回答3:


When the output goes to a pipe or non-terminal, the output format is like ls -1. If you want the columnar output, use ls -C instead.

The reason for the discrepancy is that it is usually easier to parse one-line-per-file output in shell scripts.




回答4:


Since I'm using bash, I used the following to achieve the desired output:

System:~ user# ls -C -w "$(tput cols)" | cat


来源:https://stackoverflow.com/questions/21320835/gnu-ls-command-not-outputing-the-same-over-a-pipe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!