Many of the Linux commands support patterns for file or directory names and also or some other things. Commands like ls, mv, rm, and cp support patterns wildcard characters.
Then patterns are created using special characters, which are called Wildcards. This mechanism of providing a pattern to a command is also known as Globbing.
Using the wildcards we can construct very complex patterns for filename or directory name patterns.
In this article, we are discussing the special characters used for the patterns.
Wildcards
Here are the wildcard characters-
Wildcard | Description |
---|---|
* | Any characters any number of times |
? | Any character single-time. Exactly one character. |
[char_list] | Any character from the char_list |
[!char_list] | Any character that is not in the char_list |
[[:char_class:]] | Any character belongs to :char_class: |
Character Classes
Here are the classes that we can use as character classes-
Character Class | Description |
---|---|
[[:alnum:]] | Alphanumeric characters (letter or number) |
[[:alpha:]] | Alphabetic character only(any case upper or lower) |
[[:digit:]] | Digit only |
[[:lower:]] | Lowercase character only |
[[:upper:]] | Upper case character only |
Examples
Let’s take a look at a few examples of using patterns, and how those patterns reflect-
Command | Result(example) |
---|---|
ls *.yml | abc.yml docker-compose.yml test.yml |
ls *.log | error.log apache.log mail.log |
ls error*.log | error_1.log error_3.log error_backup.log |
ls file? | file1 fileA file2 |
ls error?.log | error1.log error2.log |
ls error[127].log | error1.log error2.log error7.log |
ls error[!127].log | errorA.log error3.log error5.log |
ls error[[:alnum:]].log | error1.log error2.log errorA.log errorb.log |
ls error[[:digit:]].log | error1.log error2.log error7.log |
ls error[[:upper:]].log | errorA.log errorB.log |
ls *[[:upper:]].log | testA.log testB.log abcD.log aE.log |
ls backup-??-20*.csv | backup-04-2024.csv backup-02-2021.csv backup-01-2000abc.csv |
ls report_[[:digit:]]*.pdf | report_1dec.pdf report_9123.pdf |
ls image_[!abc]*.jpg | image_kabc.jpg image_n1.jpg |
ls file_[[:lower:][:digit:]]*.log | file_a3$a.log |
ls *[![:digit:]].{jpg,png,gif} | 100a.jpg abc.jpg first.png |
ls ????[!a-z]*.txt | 1234K.txt AbCdKKK.txt |
ls {doc,report}_??[[:upper:]]*[!xyz].{pdf,docx} | doc_12BK.pdf report_99A-3233.docx |