Listing the results of the du command in alphabetical order

Michael O'Reggio picture Michael O'Reggio · Nov 19, 2012 · Viewed 15.9k times · Source

How can I list the results of the du command in alphabetical order?

I know I can use the find command to list them alphabetically, but without the directory size, I also use the -maxdepth option for both commands so that the listing only goes down one subdirectory.

Here's the question in italics:

Write a shell script that implements a directory size analyzer. In your script you may use common Linux commands. The script should list the disk storage occupied by each immediate subdirectory of a given argument or the current directory (if no argument is given) with the subdirectory names sorted alphabetically. Also, list the name of the subdirectory with the highest disk usage along with its storage size. If more than one subdirectory has the same highest disk usage, list any one of those subdirectories. Include meaningful brief comments. List of bash commands applicable for this script includes the following but not limited: cat, cut, du, echo, exit, for, head, if, ls, rm, sort, tail, wc. You may use bash variables as well as temporary files to hold intermediate results. Delete all temporary files at the end of the execution.

Here is my result after entering du $dir -hk --max-depth=2 | sort -o temp1.txt then cat temp1.txt in the command line:

12      ./IT_PLAN/Inter_Disciplinary
28      ./IT_PLAN
3       ./IT_PLAN/Core_Courses
3       ./IT_PLAN/Pre_reqs
81      .
9       ./IT_PLAN/IT_Electives

It should look like this:

28      ./IT_PLAN
3       ./IT_PLAN/Core_Courses
12      ./IT_PLAN/Inter_Disciplinary
9       ./IT_PLAN/IT_Electives
The subdirectory with the maximum disk space use:
28      ./IT_PLAN

Once again, I'm having trouble sorting the results alphabetically.

Answer

Gilles Quenot picture Gilles Quenot · Nov 19, 2012

Try doing this :

du $dir -hk --max-depth=2 | sort -k2

-k2 is the column number 2

See http://www.manpagez.com/man/1/sort/