How to Exclude Directories When Listing Files in Linux/Unix Systems


1 views

When working with command-line operations, the ls command's default behavior includes both files and directories in its output. This becomes problematic when you specifically need to work with regular files only.

The most reliable method is using find with proper filters:

find . -maxdepth 1 -type f

This command:

  • Scans the current directory (.)
  • Doesn't recurse into subdirectories (-maxdepth 1)
  • Only lists files (-type f)

For users who prefer sticking with ls, you can combine it with grep:

ls -p | grep -v '/$'

Explanation:

  • -p flag appends / to directory names
  • grep -v inverts the match
  • The pattern /$ matches lines ending with /

To include hidden files (those starting with .) while still excluding directories:

find . -maxdepth 1 -type f -name ".*" -o -type f ! -name ".*"

For directories with thousands of files, find performs better than the ls|grep combination. The -maxdepth option prevents unnecessary directory traversal.

Count only files in current directory:

find . -maxdepth 1 -type f | wc -l

List files with specific extensions (excluding directories):

find . -maxdepth 1 -type f -name "*.txt"

In bash, you can use extended globbing (requires shopt -s extglob):

ls -d !(*/)

Note this only works in shells that support extended pattern matching.


When working with Linux/Unix systems, the ls command is fundamental for file listing. However, its default behavior includes both files and directories in the output, which isn't always desired.

The simplest way to exclude directories is using the -p flag combined with grep:

ls -p | grep -v '/$'

Explanation of flags:

  • -p appends / indicator to directories
  • grep -v inverts the match to exclude lines ending with /

For more control, consider these alternatives:

Using find Command

find . -maxdepth 1 -type f

This lists only files (-type f) in current directory (-maxdepth 1).

ls with Perl Regex

ls -l | perl -nle 'print if !/^d/'

This excludes lines starting with 'd' (directory indicator in long listing).

Common real-world use cases:

Listing Only PHP Files

ls -p | grep -v '/$' | grep '\.php$'

Counting Non-Directory Files

ls -p | grep -v '/$' | wc -l

To include hidden files (excluding directories):

ls -Ap | grep -v '/$'

Where -A shows hidden files (except . and ..).