![什么是正确的 find -exec 语法](https://linux22.com/image/570776/%E4%BB%80%E4%B9%88%E6%98%AF%E6%AD%A3%E7%A1%AE%E7%9A%84%20find%20-exec%20%E8%AF%AD%E6%B3%95.png)
我想删除特定文件夹中大于 2MB 的文件。因此我运行了:
find . -size +2M
我得到了两个文件的列表
./a/b/c/文件1
./a/f/g/文件2
然后我运行:
find . -size +2M -exec rm ;
我收到了错误信息Find: missing argument to -exec
我检查了手册页中的语法,它说-exec command ;
所以我尝试
find . -size +2M -exec rm {} +
并且它有效。我理解 {} 使其执行类似命令,rm file1 file2
而不是rm file1; rm file2;
。
那么为什么第一个没有起作用呢?
回答:
我想我只需要读几遍手册就能最终理解它的意思。尽管第一个例子没有显示 {},但在所有情况下都需要括号。然后根据所需的方法添加 \; 或 +。不要只阅读标题。还要阅读说明。明白了。
答案1
您可以使用以下任意一种形式:
find . -size +2M -exec rm {} +
find . -size +2M -exec rm {} \;
分号应该被转义!
答案2
-exec rm {} \;
你可以使用.. man find
-exec command ;
Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until
an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere
it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these
constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES
section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is
executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should
use the -execdir option instead.
-exec command {} +
This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending
each selected file name at the end; the total number of invocations of the command will be much less than the number of matched
files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is
allowed within the command. The command is executed in the starting directory.
答案3
为了提高效率,通常最好使用 xargs:
$ find /path/to/files -size +2M -print0 | xargs -0 rm