skip to Main Content

I need help with a bash script. The problem is that I want to sort all the files in order of size, but I only need files, not folders,and to show me their size as well.
I have this code but folders also appear:

read -p "Enter the size of the top: " MARIMETOP
du  -a | sort -n -r | head -n $MARIMETOP | /usr/bin/awk 'BEGIN{ pref[1]="K";  pref[2]="M"; pref[3]="G";} { total = total + $1; x = $1; y = 1; while( x  > 1024 ) { x = (x + 1023)/1024; y++; }  printf("%g%st%sn",int(x*10)/10,pref[y],$2); } END { y = 1; while(  total > 1024 ) { total = (total + 1023)/1024; y++; } ; }'

3

Answers


  1. This will print all regular files in the current directory and subdirectories sorted by size:

    find . -type f -print0 | xargs -0 -n100000 ls -Sl
    

    or if you want only size and filenames:

    find . -type f -print0 | xargs -0 -n100000 stat -f "%z %N" | sort -n -k1 -r
    

    With the -n100000 flag this will handle at most 100000 files found by find.

    Login or Signup to reply.
  2. find from GNU findutils can print the file size

    find . -type f -printf '%st%pn' | sort -k1,1nr
    
    • %s = file size
    • %p = file path (use %f for just the file’s basename)
    Login or Signup to reply.
  3. While the OP tagged the question by bash, he said in a comment that a zsh solution would also be OK. In zsh you could write it as

    du *(.OL)
    

    Explanation:

    .   : Only consider plain files
    O   : Sort descending
    L   : Sorting criterium is the length of the file
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search