glob 语法备忘
Last updated
Last updated
-> % tree .
.
├── a1.c
├── a2.py
├── a3.cpp
└── foo
├── bar
│ ├── d1.py
│ ├── d2.cpp
│ └── d3.c
├── baz
│ ├── b1.py
│ ├── b2.c
│ └── b3.cpp
├── c1.py
├── c2.cpp
└── c3.c-> % python
Python 3.9.13 | packaged by conda-forge | (main, May 27 2022, 17:00:33)
[Clang 13.0.1 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from pathlib import Path
>>> r = Path('.').absolute(); r
PosixPath('/Users/huay/tmp/glob_test')
# a*
>>> for p in r.glob('a*'): print(p)
...
/Users/huay/tmp/glob_test/a1.c
/Users/huay/tmp/glob_test/a3.cpp
/Users/huay/tmp/glob_test/a2.py
# a[13]*
>>> for p in r.glob('a[13]*'): print(p)
...
/Users/huay/tmp/glob_test/a1.c
/Users/huay/tmp/glob_test/a3.cpp
# a[!13]*
>>> for p in r.glob('a[!13]*'): print(p)
...
/Users/huay/tmp/glob_test/a2.py
# *.c*
>>> for p in r.glob('*.c*'): print(p)
...
/Users/huay/tmp/glob_test/a1.c
/Users/huay/tmp/glob_test/a3.cpp
# */*.c*
>>> for p in r.glob('*/*.c*'): print(p)
...
/Users/huay/tmp/glob_test/foo/c2.cpp
/Users/huay/tmp/glob_test/foo/c3.c
# **/*.cpp
>>> for p in r.glob('**/*.cpp'): print(p)
...
/Users/huay/tmp/glob_test/a3.cpp
/Users/huay/tmp/glob_test/foo/c2.cpp
/Users/huay/tmp/glob_test/foo/baz/b3.cpp
/Users/huay/tmp/glob_test/foo/bar/d2.cpp
# *.{py, cp*} Python 不支持
>>> for p in r.glob('*.{py, cp*}'): print(p)
...
# *.?
>>> for p in r.glob('*.?'): print(p)
...
/Users/huay/tmp/glob_test/a1.c
# */*.?
>>> for p in r.glob('*/*.?'): print(p)
...
/Users/huay/tmp/glob_test/foo/c3.c
# */*/*.?
>>> for p in r.glob('*/*/*.?'): print(p)
...
/Users/huay/tmp/glob_test/foo/baz/b2.c
/Users/huay/tmp/glob_test/foo/bar/d3.c-> % ll a[\!13]*
-rw-r--r-- 1 huay staff 0B 8 26 18:01 a2.py
-> % ll a[^13]*
-rw-r--r-- 1 huay staff 0B 8 26 18:01 a2.py
-> % ll *.{py,cp*}
-rw-r--r-- 1 huay staff 0B 8 26 18:01 a2.py
-rw-r--r-- 1 huay staff 0B 8 26 18:01 a3.cpp