Search code examples
bashfindls

Bash script to find specific type of files with absolute path and sort them by size


In bash, how can I search for files of a specific type (say "*.txt") in a directory and its sub-directories. Then display the files in descending order of size along with its size and full path.

I tried the following but it doesn't work.

find . -type f -name "*.txt" -print0 | ls -sS

How can I do this?


Solution

  • You can use GNU find's printf option to accomplish this:

    find "$PWD" -type f -name '*.txt' -printf "%s %h/%f\n" | sort -rg
    

    To show the size in KBs instead of bytes:

    find "$PWD" -type f -name '*.txt' -printf "%k %h/%f\n" | sort -rg