Sample Header Ad - 728x90

How to limit the number of files printed by ls and print them in columns like ls prints normally?

3 votes
2 answers
744 views
Here is extension of the question: [How do I limit the number of files printed by ls?](https://unix.stackexchange.com/q/21471/585416) with additional condition: how to print results in as many columns as fit to the current terminal width — as ls does by default. I understand how to limit number of files by head command but I have not come up with the solution on how to print files in columns in the same way as ls does by default but after processing through pipe. I tried ls -C flag (from man ls: -C list entries by columns) with piping to cat. But its output differs from ls out:
for i in {1..30}; do touch file$i; done; echo '"ls" out:'; ls; echo '"ls -C | cat" out:'; ls -C | cat

"ls" out:
file1   file11  file13  file15  file17  file19  file20  file22  file24  file26  file28  file3   file4  file6  file8
file10  file12  file14  file16  file18  file2   file21  file23  file25  file27  file29  file30  file5  file7  file9

"ls -C | cat" out:
file1	file12	file15	file18	file20	file23	file26	file29	file4  file7
file10	file13	file16	file19	file21	file24	file27	file3	file5  file8
file11	file14	file17	file2	file22	file25	file28	file30	file6  file9
"ls" out gives 2 line. And "ls -C | cat" out gives 3 lines. Does this may be ls -C bug? I tried column command. But when file with longer name is present it gives different result than ls.
mv file30 file-with-long-name; ls
file1   file11  file13  file15  file17  file19  file20  file22  file24  file26  file28  file3  file5  file7  file9
file10  file12  file14  file16  file18  file2   file21  file23  file25  file27  file29  file4  file6  file8  file-with-long-name

ls | cat | column -c $(tput cols)
file1			file14			file19			file23			file28			file6
file10			file15			file2			file24			file29			file7
file11			file16			file20			file25			file3			file8
file12			file17			file21			file26			file4			file9
file13			file18			file22			file27			file5			file-with-long-name
ls gives 2 lines. And ls | cat | column -c $(tput cols) gives 5 lines. tput cols — calculates terminal width. Is there may be alternative to column that will not format all columns width according to the longest file name, but will do this like ls does? Is there may be alternative command to ls to achieve such printing with limiting max file numbers? (But I also would like to have similar to ls files coloring.) With each cd to another directory I want automatically to show current directory's content. This can be done with putting ls to $PROMPT_COMMAND environment variable. But there is a problem with directories that contain too many files. They will make much noise / litter in the console. I want to restrict them to limit ls output.
Asked by Anton Samokat (289 rep)
Jul 31, 2024, 08:53 AM
Last activity: Jul 31, 2024, 10:14 AM