Home > Back-end >  How to get largest file in directory in bash?
How to get largest file in directory in bash?

Time:11-07

I have a following question. In variable DIR there is unknown number of files and folders. I would like to get the name and size in bytes of the largest one in following order: name size. For example: file.txt 124.

I tried:

cd $DIR
du  -a * | sort | head -1

But it does not show the size in bytes, and it is in size name format. How can I improve it please?

CodePudding user response:

This should do the trick:

ls -larS | awk -F' {1,}' 'END{print $NF," ",$5}'

LS long listing reverse sort by Size, then Awk prints the last field $NF, and the 5th field, using a single space or multiple single spaces, as the field separator, of the last line, being the largest size (due to reverse sort order above).

Edit:

It was mentioned a space in the file name might cause an issue, my first suggestion, is dont use spaces in filenames, it is just plain wrong, but if you have to:

ls -larS | awk -F' {1,}' 'END{for (i=9; i<=NF; i ) printf $i" "; print " ",$5}'

will handle the space, or two, or three, or how ever many

CodePudding user response:

What about the following pipeline? I'm using GNU findutils and GNU coreutils. If you work on a Mac you might have to install them.

find -maxdepth 1 -type f -printf '%s %f\0' \
  | sort -z -k1,1nr \
  | head -zn1 \
  | cut -zd' ' -f2-

Explanation:

find -maxdepth 1 -type f -printf '%s %f\0'

Find files in the current folder and print them along with their filesize in bytes, zero terminated. Zero terminated because filenames may contain newlines in UNIX.

sort -z -k1,1nr

Sort the listing by the filesize in bytes, column 1, in reverse order (largest first). -z reads input zero terminated.

head -zn1

prints the first item, which is the largest, after the previous sorting. -z reads input zero terminated

cut -zd' ' -f2-

Cut off the filesize, print only the filename. -z reads input zero terminated.

CodePudding user response:

A variation which should produce the exact output requested:

find -maxdepth 1 -type f -printf "%f %s\0" \
  | sort -znr -k2 \
  | head -zn1 \
  | tr "\0" "\n"
  •  Tags:  
  • bash
  • Related