Commands.page Logo

How to List Files Excluding Patterns in Ubuntu

Managing large directories often requires filtering out specific file types or names. This article demonstrates three effective methods to list files in Ubuntu while excluding those matching a specific pattern. We will cover using grep with ls, the find command, and bash extended globbing for precise control over your output.

Using ls with grep

The simplest method involves piping the output of the ls command into grep with the invert match flag. This filters out any lines containing your specified pattern.

ls | grep -v "pattern"

Replace “pattern” with the text or extension you wish to exclude. For example, to list everything except text files, use ls | grep -v ".txt". Note that this filters text output, so it may not behave as expected if filenames contain newlines.

Using the find Command

The find utility offers more robust filtering options, especially for recursive searches. You can negate name matches using the exclamation mark.

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

This command searches the current directory (.) without going deeper (-maxdepth 1). It looks for files (-type f) that do not match (!) the specified name pattern. This method is safer for scripting and handling complex filenames.

Using Bash Extended Globbing

For native shell filtering, enable extended globbing in bash. This allows you to use extended pattern matching directly within the ls command.

shopt -s extglob
ls -d !(*pattern*)

The shopt -s extglob command enables the feature for your current session. The !(*pattern*) syntax tells the shell to list items that do not match the pattern inside the parentheses. This is efficient for interactive use within the terminal.