regex - 删除名称长于x的目录

标签 regex linux bash

我需要删除 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/

相关文章:

bash - Shell内置执行

javascript - 用方括号替换所有内容的正则表达式

php - 如何编写正则表达式从这些 URL 中提取数字?

python - 如何以列表形式获取代码的输出?

python - 在 Eclipse 中显示错误但程序正在运行

linux - 在 awk 中删除指定符号后的部分字符串

python - 用 re.sub 替换命名的捕获组

python - "equivalent"永不匹配的正则表达式的时间完全不同?

linux - 半专用服务器 (Linux) 上的 SVN 设置

linux - 循环内的 SED 命令