Listing the largest file or sub-directory in the current directory

du -ck * | sort -rn | head -11

OS X Daily posted a tip on how to find the largest file in a directory.  I have my own that uses the du UNIX utility.  The du utility displays the file system usage statistics for each file and directory argument. To use it, type du in a Terminal window. The first column of output is the number of bytes and the second column is the directory path and file. If you run this utility in a directory with lots of files a lot of stuff will scroll off the screen. Not very useful.

However, if I combine du with a few other unix commands like sort and head I get something more useful. The sort utility sorts lines of text files while the head command displays the first lines of a file. We will use these commands together in a UNIX mechanism that involves pipes. Piping simply involves taking the output of one command and sending it as the input to another command. This is one of the things that makes UNIX so powerful.

Fire up your terminal and issue the following commands:

du -ck * | sort -rn | head -11

The -ck * tells du to compute the byte total of all files and sub-directories in the current directory and output the results in kilobytes. The output of du is then fed as input to the sort utility. The -rn tells sort to output the sorted results with the largest result first. The output of sort is then fed as input to the head command. The -11 tells head to display the top 11 results. The first line will be the total bytes computed.

You can find out more about these commands by using the man command followed by the command you want information on. For example, man du, will return a description of the du command and how to use it.

What did you think of this post?