English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Here, we will see how to use Python to obtain UNIX shell style pattern matching technology. There is a namefnmatchmodule, which is used to complete the work. This module is used to compare the filename with the pattern and then return True or False based on the matching result.
First, we need to import itfnmatchStandard library module.
import fnmatch
In Unix terminals, there are some wildcards that can match patterns. They are as follows-
'*'*' Asterisk is used to match all content.
'?' Question mark is used to match a single character.
[seq] sequence is used to match characters in the sequence
[!seq] is used to match characters that are not in the sequence.
If we want to search for asterisks or question marks as characters, we must use them like this: [*] or [?]
fnmatch()
methodThisfnmatch()
The method has two parameters, namely the filename and the pattern. This function is used to check if the filename matches the given pattern. If the operating system distinguishes between uppercase and lowercase letters, the parameters will be standardized to uppercase or lowercase letters before matching.
import fnmatch import os file_pattern = 'test_f*' files = os.listdir('./unix_files) for filename in files: print('File: {}\t: {}'.format(filename, fnmatch.fnmatch(filename, file_pattern)))
Output Result
$ python3 310.UNIX_filename.py File: test_file5.txt: True File: test_file2.png : True File: test_file1.txt: True File: another_file.txt : False File: TEST_FILE4.txt : False File: abc.txt : False File: test_file3.txt: True $
filter()
methodThisfilter()
The method also has two parameters. The first is the name, and the second is the pattern. This pattern finds the list of matching filenames from all the filenames list.
import fnmatch import os file_pattern = 'test_f*' files = os.listdir('./unix_files) match_file = fnmatch.filter(files, file_pattern) print('All files:' + str(files)) print('\nMatched files:' + str(match_file))
Output Result
$ python3 310.UNIX_filename.py All files:['test_file5.txt', 'test_file2.png', 'test_file1.txt', 'another_file.txt', 'TEST_FILE4.txt', 'abc.txt', 'test_file3.txt' Matched files:['test_file5.txt', 'test_file2.png', 'test_file1.txt', 'test_file3.txt' $
translate()
methodThistranslate()
The method takes one parameter. The parameter is a pattern. We can use this function to convert shell-style patterns to another pattern to match with regular expressions in Python.
import fnmatch, re file_pattern = 'test_f*.txt' unix_regex = fnmatch.translate(file_pattern) regex_object = re.compile(unix_regex) print('Regular Expression:' + str(unix_regex)) print('Match Object:' + str(regex_object.match('test_file_abcd123.txt')))
Output Result
$ python3 310.UNIX_filename.py Regular Expression:(?s:test_f.*\.txt)\Z Match Object:<_sre.SRE_Match object; span=(0, 21), match='test_file_abcd123.txt'> $