【问题标题】:linux command to empty all files of a directory [closed]linux命令清空目录的所有文件[关闭]
【发布时间】:2013-01-11 22:59:03
【问题描述】:

我想清空目录中的所有文件。我试过这个:

find myFolderPath/* -exec cat /dev/null > {} ';'

但它不起作用。我该怎么做?

【问题讨论】:

    标签: linux file command


    【解决方案1】:

    您不能直接在 find -exec 中使用重定向 (>),因为它发生在命令运行并创建名为 {} 的文件之前。要解决这个问题,您需要在新的 shell 中使用 sh -c

    另外,请注意,您不需要 cat /dev/null > file 来破坏文件。你可以简单地使用> file

    试试这个:

    find . -type f -exec sh -c '>"{}"' \;
    

    【讨论】:

    • 我找到了 find 。 -type f -exec sh -c '>"{}"' \;工作得更好。
    • Was getting error "sh: -c: line 0: syntax error near unexpected token `('" 因为某些文件名带有特殊字符,将命令更改为 find . -type f -exec sh - c '>"{}"' \;
    • 另一个改进,根据SC2156,命令应该变成find . -type f -exec sh -c '>"$1"' shell {} \;,以防止文件名中的特殊字符作为脚本的一部分执行
    【解决方案2】:

    这会做你想做的事:

    for f in *; do >$f; done
    

    【讨论】:

    • 我喜欢它,但是文件名中有空格时它会中断。
    • 如何以sudo 运行这个?
    猜你喜欢
    • 2016-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    相关资源
    最近更新 更多