the command :

du -sh $HOME/* | grep '[0-9]G\>' | sort -k 1rn | head -1

is giving me :

41G     /Users/user/Big folder

How can i extract the path to reuse it in my script ?

du -sh $HOME/* | grep '[0-9]G\>' | sort -k 1rn | head -1 | awk '{ print $2 }'

Will output


Which is unusable, where i am looking for a result like :

/Users/user/Big\ folder
  • Just replace your awk part with awk -v q="'" '{ print q$2q }'
    – cuonglm
    Apr 9, 2017 at 16:37
  • My bad, just edited my post : du -sh $HOME/* | grep '[0-9]G\>' | sort -k 1rn | head -1 | awk '{ print $2 }' Gives /Users/user/Big Apr 9, 2017 at 16:40
  • So awk -v q="'" '{ print q$2q }' will give '/Users/user/Big' but we are almost there...! Apr 9, 2017 at 16:43
  • I suspect this is an XY problem and the real answer is "quote your shell variables" Apr 9, 2017 at 16:49
  • 1
    . . . but cd "$VAR" will Apr 9, 2017 at 17:08

3 Answers 3


When doing automated processing, don't make your life more complicated by using numbers in different units. Don't pass -h to du. Then you can use simple numerical sorting on the output, and your script will still work if you have more than 1 TB in one of the directories.

du -s ~/* | sort -k 1n | tail -n1

This always prints out a line, even if the largest subdirectory contains less than 1 GB. If that's not what you want, you can replace the conditional “is the output empty” by “is the number less than the threshold”.

To extract the directory name, take the output and remove the part up to the first tab.

largest_directory=$(du -s ~/* | sort -k 1n | tail -n1)
largest_directory_size_kB=${largest_directory%%$(printf '\t')*}  # if you need the size
largest_directory=${largest_directory#*$(printf '\t')}


du -s "$HOME"/* | sort -rnk1 | LC_ALL=C sed -e "s,[^/]*\(/.*\),'\1',;q"

Without -h, du result included plain number for size, so we can easily sort it without extra grep.

Using sed to perform deletion at the first line only then quitting, we save a head invocation.

  • output is '/Users/user/Big folder', but still missing the "\ " to have '/Users/user/Big\ folder' Apr 9, 2017 at 17:03
  • @VinhFrancisGuyait The result is quoted, so the same as escaping the whitespace?
    – cuonglm
    Apr 9, 2017 at 17:05
  • Not escaping it, the idea at the end is to use the output with other command like for treatment in the script. Apr 9, 2017 at 17:09
  • @VinhFrancisGuyait So for f in '/Users/user/Big folder' ... just work as you want.
    – cuonglm
    Apr 9, 2017 at 17:10
  • true, didn't realized ! Thanks @cuonglm Apr 9, 2017 at 17:12

Another way to extract the path you want is via read command after you're done doing the du stuff and sort-ed them and then pass on to the while/read

du.. sort.. | while read x d; do echo "$d"; done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.