Problem:
You have a directory with the files:
file
file1
file22
file333
file456xyz
You'd like to match "file" followed by one or more digits, but NOT by using the asterisk, because that will match any other characters, and not by repeating [0-9] multiple times, because you're not sure how many digits there could be.
In this example, I want to match file1, file22 and file333, but I do NOT want file or file456xyz
In regex / regular expressions, you would use the postfix modifier / operator plus (+), as in file[0-9]+, or in older regex parsers that don't have plus, you could still do file[0-9][0-9]*.
But these won't work in the unix shell in bash.
Answer:
Bash file globbing patterns have an extended syntax option that allows for a prefix modifier syntax similar to that in regex, but you've got to turn it on to use it.
First call the shell options, to set extended glob patterns:
shopt -s extglob
Then try this pattern:
ls file+([0-9])
The plus has a similar meaning to what it has in regex, but is placed before the parenthesis, instead of after, and you must use parens even if you only have one character class.
If you haven't set the extended shell option you'll get a syntax error:
(from a different shell where the shopt command hasn't been issued)
ls file+([0-9])
bash: syntax error near unexpected token `('
Again, if you see this error, it's easy to fix, just do:
shopt -s extglob
And you'll probably want that in your shell script if you're writing a program, etc.
IF we had known we would only have, for example, 3 digits, we could have got away with:
ls file[0-9][0-9][0-9]
Or the fancier:
ls file[:digit:][:digit:][:digit:]
or
ls file[=0=][=0=][=0=]
or
ls file[=1=][=2=][=3=]
etc. See the man pages for bash under Pattern Matching
But again, this wouldn't work if weren't guaranteed to have exactly 3 digits.
Google searches keep referring back to regex and grep, which does NOT use the same syntax, so in this case you're better off with the man pages.
Comments