删除所有文件但将所有目录保留在 bash 脚本中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1280429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:08:16  来源:igfitidea点击:

Delete all files but keep all directories in a bash script?

bashshell

提问by Grundlefleck

I'm trying to do something which is probably very simple, I have a directory structure such as:

我正在尝试做一些可能非常简单的事情,我有一个目录结构,例如:

dir/
    subdir1/
    subdir2/
        file1
        file2
        subsubdir1/
            file3

I would like to run a command in a bash script that will delete all files recursively from dir on down, but leave all directories. Ie:

我想在 bash 脚本中运行一个命令,该命令将从 dir 向下递归删除所有文件,但保留所有目录。IE:

dir/
    subdir1/
    subdir2/
        subsubdir1

What would be a suitable command for this?

什么是合适的命令?

回答by liori

find dir -type f -print0 | xargs -0 rm

findlists all files that match certain expression in a given directory, recursively. -type fmatches regular files. -print0is for printing out names using \0as delimiter (as any other character, including \n, might be in a path name). xargsis for gathering the file names from standard input and putting them as a parameters. -0is to make sure xargswill understand the \0delimiter.

find递归地列出给定目录中与特定表达式匹配的所有文件。-type f匹配常规文件。-print0用于使用\0分隔符打印名称(因为任何其他字符,包括\n,都可能在路径名中)。xargs用于从标准输入收集文件名并将它们作为参数。-0是为了确保xargs理解\0分隔符。

xargsis wise enough to call rmmultiple times if the parameter list would get too big. So it is much better than trying to call sth. like rm $((find ...). Also it much faster than calling rmfor each file by itself, like find ... -exec rm \{\}.

xargsrm如果参数列表变得太大,多次调用是足够明智的。所以这比试图打电话要好得多。喜欢rm $((find ...)。而且它比单独调用rm每个文件要快得多,例如find ... -exec rm \{\}.

回答by John Kugelman

With GNU's findyou can use the -deleteaction:

使用 GNU,find您可以使用以下-delete操作:

find dir -type f -delete

With standard findyou can use -exec rm:

使用标准,find您可以使用-exec rm

find dir -type f -exec rm {} +

回答by Tyler McHenry

find dir -type f -exec rm {} \;

where diris the top level of where you want to delete files from

其中dir是要从中删除文件的顶级位置

Note that this will only delete regular files, not symlinks, not devices, etc. If you want to delete everything except directories, use

请注意,这只会删除常规文件,不会删除符号链接,不会删除设备等。如果要删除除目录之外的所有内容,请使用

find dir -not -type d -exec rm {} \;

回答by J?rg W Mittag

find dir -type f -exec rm '{}' +