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

Gru*_*eck 21 bash shell

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

dir/
    subdir1/
    subdir2/
        file1
        file2
        subsubdir1/
            file3
Run Code Online (Sandbox Code Playgroud)

我想在bash脚本中运行一个命令,它将从dir中递归删除所有文件,但保留所有目录.即:

dir/
    subdir1/
    subdir2/
        subsubdir1
Run Code Online (Sandbox Code Playgroud)

什么是合适的命令?

lio*_*ori 41

find dir -type f -print0 | xargs -0 rm
Run Code Online (Sandbox Code Playgroud)

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

xargsrm如果参数列表变得太大,那么就可以多次调用.所以它比试图打电话要好得多.喜欢rm $((find ...).它也比自己调用rm每个文件快得多,比如find ... -exec rm \{\}.


Joh*_*ica 10

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

find dir -type f -delete
Run Code Online (Sandbox Code Playgroud)

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

find dir -type f -exec rm {} +
Run Code Online (Sandbox Code Playgroud)


Tyl*_*nry 8

find dir -type f -exec rm {} \;
Run Code Online (Sandbox Code Playgroud)

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

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

find dir -not -type d -exec rm {} \;
Run Code Online (Sandbox Code Playgroud)


Jör*_*tag 8

find dir -type f -exec rm '{}' +
Run Code Online (Sandbox Code Playgroud)

  • `-exec`命令可以通过两种方式终止:分号或加号.如果使用分号,则会为每个文件生成一个新进程.如果使用加号,则只会生成一个进程.(嗯,实际上,如果命令行太长,那么会生成多个进程 - 基本上,它的工作方式就像`xargs`但没有所有引用问题.)说,你有两个文件,分别叫做A和B.然后,用分号产生两个过程:`rm A`和`rm B`.加上,只产生一个进程:`rm AB`. (3认同)