Can `ls` be set to only list the first X files/directories?
I'm trying to make a command which only displays the first 30 files when the ls
command is invoked. I found this method...
ls | head -30
... but it ends up spitting out the files in one long list, not formatted in a row or colored as per the .bash_profile
. So, is there any way to simply limit the output?
Solution 1:
Until asteri clarified the question, I thought John1024 had the answer. Now it seems that the following will work without the --color
option:
ls -d $(ls | head -30)
Unfortunately this is too simplistic and will fail if there are blanks in the file names. To take account of that you need the more elaborate:
ls -b | head -30 | xargs ls -d
In both cases the principle is the same: ls | head
gets the first 30 files, one per line, which are then presented as an argument list to another ls
command, which needs the -d
option in case any of the files are directories.
Solution 2:
To get coloring:
ls -l --color=always | head -30
Normally, ls
produces color only when the output is going directly to a terminal. This is generally a good thing. To override that, use --color=always
The above produces output with one file per line. If you want, space allowing, more files per line, then try:
ls -l | head -30 | column
The column utility formats its input into multiple columns. The use of color may, however, confuse it.