查找文件并删除父级目录

Find a file and delete the parent level dir

如何删除文件所在的父目录(仅上一级)并使用 find 命令找到

find . -type f -name "*.root" -size 1M

哪个returns

./level1/level1_chunk84/file.root

所以,我想递归地删除 level_chunck84 目录,例如..

谢谢

您可以尝试类似的方法:

find . -type f -name "*.root" -size 1M -print0 | \
xargs -0 -n1 -I'{}' bash -c 'fpath={}; rm -r ${fpath%%$(basename {})}'

find + xargs 组合很常见。请参考 man find,你会发现一些例子展示了如何一起使用它们。

我在这里所做的只是将 -print0 标记添加到您的原始查找语句中:

-print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs.

然后将所有内容通过管道传输到 xargs,后者可作为制作更多命令的助手:
- 执行 bash 子 shell
中的所有内容 - 将文件路径分配给变量 fpath={}
- 从文件路径

中提取 dirname

${parameter%%word} Remove matching suffix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the %'' case) or the longest matching pattern (the%%'' case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

- 最后递归删除

还有一个更短的版本:

find . -type f -name "*.root" -size 1M -print0 | \
xargs -0 -n1 -I'{}' bash -c 'fpath={}; rm -r ${fpath%/*}'