Zsh 패턴 매칭

Zsh is a powerful shell that offers advanced features and customization options. One of its standout features is the ability to perform pattern matching. Pattern matching allows you to specify a pattern and match it against filenames or strings, making it extremely useful for file manipulation and command-line tasks.

In this blog post, we will explore the various methods of pattern matching in Zsh and demonstrate how they can be used to streamline your Linux workflow.

Simple Globs

The most basic form of pattern matching in Zsh is done through globs. Globs are wildcard characters that allow you to match multiple filenames or strings.

  1. Asterisk (*): Matches any number of characters, including none.
  2. Question mark (?): Matches exactly one character.
  3. Square brackets ([]): Matches any one character listed inside the brackets.
  4. Tilde (~): Matches any one character not listed inside the brackets.

For example, to list all files with an extension of .txt in the current directory, you can use the following command:

ls *.txt

To match any file with a name that starts with file and ends with any letter, you can use:

ls file?[a-z]

Extended Globbing

Zsh also supports extended globbing, which expands upon the basic globbing functionality by providing additional pattern matching features.

  1. Double Asterisk (**): Matches files in subdirectories recursively.
  2. Extended range expressions ([::]): Matches a range of characters or a sequence of characters.
  3. Negation (~): Matches anything except what is specified.

To find all .png files in the current directory and its subdirectories, you can use the following command:

ls **/*.png

To match files with names containing three letters in the range m to p, you can use:

ls [m-p](#c3)

Brace Expansion

Zsh also supports brace expansion, which allows you to generate multiple strings by expanding a pattern inside curly braces.

For example, to create multiple directories with names folder1, folder2, and folder3, you can use the following command:

mkdir folder{1..3}

You can also combine brace expansion with globbing to perform bulk operations, such as moving or copying multiple files.

Conclusion

Zsh’s pattern matching capabilities, including globs, extended globbing, and brace expansion, provide a convenient and powerful way to manipulate files and perform command-line tasks in Linux. By understanding and utilizing these features, you can enhance your productivity and efficiency in the terminal.

This blog post has covered the basics of Zsh pattern matching. To explore further, consider experimenting with more complex patterns and exploring the Zsh documentation for additional options and advanced techniques.