How to get a DOS-type directory listing in Linux/Unix
How to sort directories like DOS does, but in Linux/UNIX
A question I've seen asked from time to time is "how do I get a DOS-style directory listing?" - that is, with the directories listed first, followed by the filenames in alphabetical order. Sorting by filemame is easy, as is sorting by date, or by status, etc. but when you want to group directories separately from files and then sort them individually it seems tricky or impossible.
In reality it is actually easy using GNU sort (from coreutils).
First you need to run ls then pipe it through sort, like so:
ls -l | sort -k 1.1,1.2 -k 8.1 -f | less
What happens here is this:
`ls -l` provides the "long" directory listing
`sort` is the utility which will sort the lines output by ls
`-k 1.1,1.2` sorts by the first field, first and second column. Since directory files have 'd' as the first character for this field, directories will be listed first
`-k 8.1` applies a second sort by the eighth field (filename), starting from the first column
`-f` tells sort to ignore case, just as the DOS `dir` command does.
Now, by default, `dir` is aliased to `ls -l` in many (all?) distributions. If you wish to change this edit /etc/bash.bashrc and search for "alias dir". Once you find it then change 'ls -l' to the command specified above. Now you have a DOS-style directory sort which lists directories first, followed by a case-insensitive alphabetical listing of files.
In a similar fashion, you can get a DOS-style directory listings where the directories are grouped but sorted by date/time, and files are grouped but sorted by date-time (You can extend it further by also adding the filename sort back, for two files with the same timestamp).
To sort by date/time you just modify the above command slightly:
ls -l | sort -k 1.1,1.2 -k 6.1 -k 7.1 -f | less
And to add an additional sort by filename (after sorting FIRST by directory/file byte, THEN by date, THEN by time) run the following command:
ls -l | sort -k 1.1,1.2 -k 6.1 -k 7.1 -k 8.1 -f | less
Enjoy! :)
