xargs管道包含多个命令



我试图找到所有超过30天的文件,在目录中键入。pkl,获得找到的文件的父目录并删除它们。我的解决方案看起来像这样:

find path_to_dir/.cache -type f -name "*.pkl" -mtime +30 |
xargs dirname | xargs rm -r

是否有一种方法来避免双xargs?另外,我的另一个任务是删除所有日志文件,但不删除父目录。例如

find path_to_dir -type f -name "*.log" -mtime +30 -delete

我可以在一行中完成上面的操作而不需要代码复制吗?

如果您正在使用GNU查找,您可以在-printf命令中使用%h令牌:

find path_to_dir/.cache -type f -name '*.pkl' -mtime +30 -printf '%h' |
xargs -0 rm -r

对于两个操作的组合,像这样可以工作:

find path_to_dir/ -mtime +30 -type f ( -name '*.pkl' -printf '%h' -o -name '*.log' -print0 ) |
xargs -0 rm -r

…但这假设您可以为这两个操作使用相同的起始前缀(在您的示例中,您在第一种情况下使用path_to_dir/.cache,在第二种情况下使用path_to_dir)。

最新更新