linux - Find the largest file in directory without size in output

06
2014-04
  • artsel

    I need to find the biggest file

    1. Only one file should be listed
    2. Search should work in given directory and subdirectories
    3. Output should display absolute path to the file with filename

      find "$PARAM" -type f | xargs ls -1S | head -n 1
      

    works but gives me errors like

    ls: cannot access Over: No such file or directory

  • Answers
  • glenn jackman

    Don't parse ls. Let find do that work for you:

    find "$PARAM" -type f -printf "%s\t%p\n" | sort -n | tail -n 1 | cut -f 2- 
    

    Without find, we can use bash's recursive globbing:

    shopt -s globstar nullglob
    stat -c $'%s\t%F\t%n' ** \
    | awk -F'\t' '$2 == "regular file"' \
    | sort -n \
    | tail -n 1 \
    | cut -f 3-
    

    The stat on OSX will have different but equivalent options for stat, and may spit out a different string for "regular file".


  • Related Question

    linux - Unix - List all directories and subdirectories, excluding directories without files
  • ftiaronsem

    I would like to list all the directories and sub directories in and below the current path. Since I only wanted to display directories I came up with the follwing command:

    find -type d -exec ls -d1 {} \; | cut -c 3-
    

    This prints out for example

    webphone
    music
    finance
    finance/banking
    finance/realestate
    finance/trading
    finance/other
    finance/moneylending
    finance/insurance
    webradio
    webtv
    

    The problem I have right now is, that the directory finance is listed. finance contains no files yust the sub directories you see above. What I want to achieve is the following output:

    webphone
    music
    finance/banking
    finance/realestate
    finance/trading
    finance/other
    finance/moneylending
    finance/insurance
    webradio
    webtv
    

    In this list the directory finance is not listed. Therefore I need your adive of how to filter directories which contain no files (only subdirectories).

    Thanks in advance

    ftiaronsem


  • Related Answers
  • Gilles

    Here's one way: list all regular files, strip away the file basenames, and remove duplicates.

    find . -type f | sed 's!/[^/]*$!!' | sort -u
    

    If you want to strip the leading ./:

    find . -type f | sed -e 's!/[^/]*$!!' -e 's!^\./!!' | sort -u
    
  • udo

    I consider installing tree:

    • sudo apt-get install tree

    and then run

    • tree -d /path/to/start/dir

    to display directories only.

    Example:

    root@X100e:~# tree -d /var/cache/
    /var/cache/
    ├── apache2
    │   └── mod_disk_cache
    ├── apt
    │   └── archives
    │       └── partial
    ├── binfmts
    ├── cups
    │   └── rss
    ├── debconf
    ├── dictionaries-common
    ├── flashplugin-installer
    ...