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.
Using the du and sort Commands We can use du and sort commands to list and sort files according to their size: $ du -ah --max-depth=1 | sort -h 451M ./dir2 751M ./dir1 1.2G ./file4.
The du command is a standard Linux/Unix command that allows a user to gain disk usage information quickly. It is best applied to specific directories and allows many variations for customizing the output to meet your needs. As with most commands, the user can take advantage of many options or flags.
The sort command arranges data alphabetically or numerically in ascending or descending order.
The sort command sorts the contents of a file, in numeric or alphabetic order, and prints the results to standard output (usually the terminal screen).
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/
du $dir -hk --max-depth=2 |awk '{print $2"\t"$1}'|sort -d -k1 -o temp1.txt
and if you want to remove the ./ path
du $dir -hk --max-depth=2 |awk '{print $2"\t"$1}'|sed -e 's/\.\///g'|sort -d -k1 -o temp1.txt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With