So I've got the following files in the tmp directory:
file.0
file.1
file.t9
file.22
file.4444
if I wanted to list only the files that end in '.digits' (0, 1, 22, 4444) but not (t9) I could try and use wildcards such as this:
ls tmp/file.{[0-9],[0-9][0-9],[0-9][0-9][0-9],[0-9][0-9][0-9][0-9]}
however I get the following results with the ugly error
ls: cannot access tmp/file.[0-9][0-9][0-9][0-9]: No such file or directory
file.0
file.1
file.22
file.4444
I've also tried using {0..999} but that also results in the same sorts of errors (and a lot more of them). Any clues as how to do this without errors from the experts?
At least in bash 4, when the extglob
shell option is enabled:
shopt -s extglob
ls /tmp/file.+([0-9])
The pattern +([0-9])
there matches one or more digits.
You can read more about this in the Pattern Matching section of man bash
.
UPDATE
Actually, as @chepner pointed out, since extglob
was introduced in version 2.02, this should work in pretty much every bash
you come across today, unless you pulled your distro out of a rock or something.
You can use ls
just to list all the files then filter the output of that through grep
:
ls -1 | grep -E '\.[0-9]+$'
as per the following test:
pax> printf 'file.0\nfile.1\nfile.t9\nfile.22\nfile.4444\n' | grep -E '\.[0-9]+$'
file.0
file.1
file.22
file.4444
The -E
gives you extended regular expressions so that the +
modifier works. If that's not available to you, you can use the \.[0-9][0-9]*$
regex instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With