如何在“find”的“-exec”属性中使用“if”?

v01*_*dya 3 command-line bash find

我有一个包含许多文件对的目录。每个非文本文件都有一个文本描述伙伴。例如,目录可能如下所示:

a.jpg
a.jpg.text
b.ogv
b.ogv.text
cd ef.JpG
cd ef.JpG.text
Run Code Online (Sandbox Code Playgroud)

我想确认没有松散的文本文件(已删除内容的描述文件)。所以我试图执行以下操作:

find . -name '*.text' -exec if [ ! -f `basename -s .text {}` ]; then echo {}; fi \;
Run Code Online (Sandbox Code Playgroud)

但是,现在我收到一个错误:

bash: syntax error near unexpected token `then'
Run Code Online (Sandbox Code Playgroud)

Rad*_*anu 5

您只是不能以您希望的方式在命令操作if内部使用。这是因为以下原因:-execfind

  • -exec操作需要一个命令。这是来自man find(在我终端的 697 行某处):
    -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 sec?
          tion for examples of the use of the -exec option.  The specified
          command is run once for each matched file.  The command is  exe?
          cuted  in  the starting directory.   There are unavoidable secu?
          rity 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 invoca?
          tions 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.
Run Code Online (Sandbox Code Playgroud)

现在,要完成您的愿望,您实际上并不需要if-exec. 只需在 中进行测试-exec,然后使用-printman find有关更多信息,请参阅):

find . -name '*.text' -exec $SHELL -c '[ ! -f ${1%.*} ]' $SHELL '{}' ';' -print
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用 bash 脚本,如下所示:

find . -name '*.text' -exec my_if {} \;
Run Code Online (Sandbox Code Playgroud)

cat ~/bin/my_if在我的情况下,其中给出了以下输出:

#!/bin/bash
if [ ! -f $(basename -s .text "$1") ]; then echo "$1"; fi
Run Code Online (Sandbox Code Playgroud)

最后,我认为所有使用 bash 的普通人都会使用:

for f in *.text; do if [ ! -f $(basename -s .text "$f") ]; then echo "$f"; fi; done
Run Code Online (Sandbox Code Playgroud)