I have a bunch of random folders, some of them are hidden (beginning with a period). I want to list all of them, sorted by their sizes.
I have something on the lines of this in mind:
ls -d -1 -a */ | xargs du -s | sort
But the ls ...
part of it doesn't show hidden files. I know some questions have been asked before on the same topic, but the answers never include a way to include hidden files. Or if it does, it uses the long format, hence making the output incompatible with the rest of the command.
Best Answer
Parsing the output of
ls
is always problematic. You should always use a different tool if you mean to process the output automatically.In your particular case, your command was failing -- not because of some missing or incompatible argument to
ls
-- but because of the glob you were sending it. You were askingls
to list all results including hidden ones with-a
, but then you were promptly asking it to only list things that matched the*/
glob pattern which does not match things beginning with.
and anythingls
might have done was restricted to things that matched the glob. You could have used.*/
as a second glob to match hidden directories as well, or you could have left the glob off entirely and just letls
do the work. However, you don't even needls
for this if you have a glob to match.One solution would be to skip the
ls
entirely and just use shell globing:*Another way which might be overkill for this example but is very powerful in more complex situations would be to use
find
:*Explanation:
find ./
starts a find operation on the current directory. You could use another path if you like.-type d
finds only things that are directories-maxdepth 1
tells it only to find directories in the current directory, not to recurse down to sub-directories.-exec [command] [arguments] {} +
works much likexargs
, butfind
gets to do all the heavy lifting when it comes to quoting and escaping names. The{}
bit gets replaced with the results from the find.du -s
you know* Note that I used the
-n
operator forsort
to get a numeric sorting which is more useful in than alphabetic in this case.