How to list only files and not directories of a directory Bash?

前端 未结 9 1083
旧巷少年郎
旧巷少年郎 2020-12-07 21:54

How can I list all the files of one folder but not their folders or subfiles. In other words: How can I list only the files?

9条回答
  •  孤城傲影
    2020-12-07 22:28

    • carlpett's find-based answer (find . -maxdepth 1 -type f) works in principle, but is not quite the same as using ls: you get a potentially unsorted list of filenames all prefixed with ./, and you lose the ability to apply ls's many options;
      also find invariably finds hidden items too, whereas ls' behavior depends on the presence or absence of the -a or -A options.

      • An improvement, suggested by Alex Hall in a comment on the question is to combine shell globbing with find:

            find * -maxdepth 0 -type f  # find -L * ... includes symlinks to files
        
        • However, while this addresses the prefix problem and gives you alphabetically sorted output, you still have neither (inline) control over inclusion of hidden items nor access to ls's many other sorting / output-format options.
    • Hans Roggeman's ls + grep answer is pragmatic, but locks you into using long (-l) output format.


    To address these limitations I wrote the fls (filtering ls) utility,

    • a utility that provides the output flexibility of ls while also providing type-filtering capability,
    • simply by placing type-filtering characters such as f for files, d for directories, and l for symlinks before a list of ls arguments (run fls --help or fls --man to learn more).

    Examples:

    fls f        # list all files in current dir.
    fls d -tA ~  #  list dirs. in home dir., including hidden ones, most recent first
    fls f^l /usr/local/bin/c* # List matches that are files, but not (^) symlinks (l)
    

    Installation

    Supported platforms

    • When installing from the npm registry: Linux and macOS
    • When installing manually: any Unix-like platform with Bash

    From the npm registry

    Note: Even if you don't use Node.js, its package manager, npm, works across platforms and is easy to install; try
    curl -L https://git.io/n-install | bash

    With Node.js installed, install as follows:

    [sudo] npm install fls -g
    

    Note:

    • Whether you need sudo depends on how you installed Node.js / io.js and whether you've changed permissions later; if you get an EACCES error, try again with sudo.

    • The -g ensures global installation and is needed to put fls in your system's $PATH.

    Manual installation

    • Download this bash script as fls.
    • Make it executable with chmod +x fls.
    • Move it or symlink it to a folder in your $PATH, such as /usr/local/bin (macOS) or /usr/bin (Linux).

提交回复
热议问题