4

I need to find the largest file in the current and subsequent directory. I tried

ls -Rlh | awk '{print $3 " " $5 " " $9}' 

but do not know if it is ok, how to sort and select the largest file.

Archemar
  • 31,183
  • 18
  • 69
  • 104
user91991993
  • 155
  • 1
  • 5

2 Answers2

7

GNU find + sort + head solution (for any directory depth level), assuming file paths don't contain newline characters:

find . -type f -printf "%s %p\n" | sort -nr | head -1
  • %s - format specificator pointing to file size (in bytes)
  • %p - format specificator pointing to file name
  • sort -nr - sort records numerically in reversed order
  • head -1 - print the TOP first line/record

To get a human-readable file size value - extend the pipeline with GNU numfmt command (if supported):

find . -type f -printf "%s %p\n" | sort -nr | head -1 | numfmt --to=si
RomanPerekhrest
  • 29,703
  • 3
  • 43
  • 67
2

With zsh, for the biggest regular file:

ls -ld -- **/*(.DOL[1])

(of course you can replace ls -ld -- with any command. If using GNU ls or compatible see also the -h option for human readable sizes)

  • .: only regular files (not directories, symlinks, devices, fifos...)
  • D: include hidden ones and descend into hidden dirs
  • OL: reverse-ordered by size (Length).
  • [1]: only the first match.

If there are ties, you'll get any one of them at random. If you want the first in alphabetical order, add an extra on (order by name) to sort ties alphabetically.

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
  • I might do something wrong but it does not work – user91991993 Nov 20 '17 at 16:12
  • @JamesW, I suspect you missed the _"With `zsh`"_ part. What shell are you trying it in? In which way does it not work? – Stéphane Chazelas Nov 20 '17 at 16:16
  • I am running bash. So I have to put that in a script, right and execute with zsh. Can I do it straight from the command line? – user91991993 Nov 20 '17 at 16:29
  • 1
    From `bash`, you can always do `zsh -c 'ls -ld -- **/*(.DOL[1])'` but if you're often finding yourself looking for the _quickest way_, you may want to consider switching your shell to `zsh` (also for _safest way_ , _best way_ and _more efficient way_). – Stéphane Chazelas Nov 20 '17 at 16:32