brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: [0-9] and [!0-9] in a shell glob match one character from a set

Shell
~/tips/tip-shell-glob-brackets-ranges

ls

Pick files by a digit or letter in a fixed spot, without regex.

* and ? match anything. When you need one character of a certain kind, square brackets do it, in every shell.

Brackets match exactly one character from the set or range inside:

ls
# log1  log2  log10  logx
echo log[0-9]
# log1 log2
echo log[0-9][0-9]
# log10
echo log[!0-9]
# logx

[!...] turns the set around and matches any character that is not in it. Bash also accepts [^...], but ! is the POSIX form and works in sh too.

I like this for rotated logs: rm syslog.[2-9].gz removes the older ones and keeps syslog.1.gz. Run it with echo or ls first to see the list before anything is deleted.

Ranges like [a-z] depend on the locale in some shells and can then also match capital letters. The character classes avoid that: [[:digit:]], [[:lower:]], [[:upper:]] and [[:alpha:]] mean the same thing everywhere. Note the double brackets, the outer pair is the set and [:digit:] sits inside it. And a bracket matches one character, not a number, so [0-15] means 0, 1 or 5.

Further reading: Bash manual: Pattern Matching

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link