Bash : Pattern Matching

De Justine's wiki
Aller à la navigation Aller à la recherche

Issu de : https://www.linuxjournal.com/content/pattern-matching-bash  

Ressources :

https://www.tldp.org/LDP/abs/html/globbingref.html

Globbing

Il s'agit ici de "globbing", c'est-à-dire, l'expansion des fonctionnalités des wildcards (* et ?). Il ne s'agit donc pas ici d'expression régulières, bien que celles-ci puissent être utilisées conjointement avec du globbing.   Les patterns de glob de Bash sont les suivants :

Pattern Description
* Match zero or more characters
? Match any single character
[...] Match any of the characters in a set
?(patterns) Match zero or one occurrences of the patterns (extglob)
*(patterns) Match zero or more occurrences of the patterns (extglob)
+(patterns) Match one or more occurrences of the patterns (extglob)
@(patterns) Match one occurrence of the patterns (extglob)
!(patterns) Match anything that doesn't match one of the patterns (extglob)
 Exemples :

<source> $ ls a.jpg b.gif c.png d.pdf ee.pdf

$ ls *.jpg a.jpg

$ ls ?.pdf d.pdf

$ ls [ab]* a.jpg b.gif

$ shopt -s extglob # turn on extended globbing

$ ls ?(*.jpg|*.gif) a.jpg b.gif

$ ls !(*.jpg|*.gif) # not a jpg or a gif c.png d.pdf ee.pdf </source>

<source> $ ls *.pdf ee.pdf e.pdf .pdf

$ls ?(e).pdf # zero or one "e" allowed e.pdf .pdf

$ ls *(e).pdf # zero or more "e"s allowed ee.pdf e.pdf .pdf

$ ls +(e).pdf # one or more "e"s allowed ee.pdf e.pdf

$ ls @(e).pdf # only one e allowed e.pdf </source>


Les glob sont juste une autre façon de trouver des patterns spécifique en bash, et on peut les utiliser un peu partout; après un ==, dans un case, etc. <source> $ shopt +s extglob

$ a=something $ if any)thing ; then echo yes; else echo no; fi yes

$ a=anything $ if any)thing ; then echo yes; else echo no; fi yes

$ a=nothing $ if any)thing ; then echo yes; else echo no; fi no </source>