我需要删除 Linux shell 上名称长度超过 4 个字符的目录。 但不计算子目录的长度。
例如:
/12345/.. <= Should be deleted
/123456/.. <= Should be deleted
/1234/12345 <= Should NOT be deleted
/1234/123456 <= Should NOT be deleted
更新: 明白了:
find -maxdepth 1 -regextype posix-egrep -type d -regex '.*[^/]{4}' -exec rm -rf {} +
最佳答案
要删除 bash
中所有包含 5 个或更多字符的目录,您可以执行以下操作:
rm -rf ?????*/
该表达式不是正则表达式,而是使用一组通配符来指定文件名或路径的 glob 模式。
基本上,如果您想要保留 4 个或更少字符的目录,则需要删除包含 5 个或更多字符的所有内容,因此使用 5 个 ?
和单个 *
。 /
表示目录。
man bash
*
:: Matches any string, including the null string. When the globstar shell option is enabled, and*
is used in a pathname expansion context, two adjacent*
s used as a single pattern will match all files and zero or more directories and subdirectories. If followed by a/
, two adjacent*
s will match only directories and subdirectories.
?
:: Matches any single character.
$ find .
.
$ mkdir -p {1,12,123,1234,12345,123456}/{123,12345}
$ touch foobar
$ rm -rf ?????*/
$ find .
.
./123
./123/12345 <= subdirectory with 5 or more not deleted
./123/123
./foobar <= the file is still here
./1234
./1234/12345
./1234/123
./12
./12/123
./12/12345
./1
./1/12345
./1/123
关于regex - 删除名称长于x的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48707335/