fnmatch - Linux


Overview

fnmatch is a shell command-line utility that performs wildcard pattern matching. It tests whether a filename matches the specified pattern. This is particularly useful for selecting files from a directory or filtering filenames for specific operations.

Syntax

fnmatch PATTERN FILENAME

Parameters:

  • PATTERN: A wildcard pattern to match against the filename.
  • FILENAME: The filename to match.

Options/Flags

None

Examples

Simple Usage:

fnmatch '*.*' 'README.md'

Output: true (matches any filename with any extension)

Complex Usage:

fnmatch '*.{txt,md}' 'test.txt'

Output: true (matches filenames ending in either .txt or .md)

Common Issues

  • Ambiguous Patterns: If multiple patterns match the filename, the results may be unpredictable. Use specific patterns or enclose them in single quotes to avoid ambiguity.

Integration

fnmatch can be integrated with other commands and shell constructs:

  • File Selection: Use fnmatch in a find command to select files based on their names.
  • Filename Filtering: Filter filenames from a list using grep and fnmatch.
  • Shell Scripts: Implement filename matching logic in shell scripts for automated tasks.

Related Commands

  • basename: Returns the filename without the directory path.
  • dirname: Returns the directory path without the filename.
  • globstar: Performs recursive wildcard matching.