我正在尝试做一些可能非常简单的事情,我有一个目录结构,例如:
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)
        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)
        find dir -type f -exec rm '{}' +
Run Code Online (Sandbox Code Playgroud)