【问题标题】:Bash find: changing matched name for use in -execBash 查找:更改匹配名称以在 -exec 中使用
【发布时间】:2011-11-13 05:01:37
【问题描述】:

我正在编写一个部署脚本,我需要针对目录中的所有 .less 文件运行一个 less 编译器。使用以下 find 命令很容易做到这一点:

find -name "*.less" -exec plessc {} {}.css \;

在包含名为main.less 的文件的文件夹上运行此命令后,我留下了一个名为main.less.css 的文件,但我希望它是main.css

我知道我可以使用以下命令轻松删除生成文件的 .less 部分:rename 's/\.less//' *.css 但我希望了解有关使用 -exec 的新知识。

在-exec参数中使用匹配的文件名是否可以修改?

谢谢!

【问题讨论】:

    标签: bash shell find


    【解决方案1】:

    您的 find 命令使用了几个非标准的 GNU 扩展:

    • 您没有说明在哪里找到,这是 POSIX 中的错误,但 GNU find 在这种情况下选择当前目录
    • 您使用非隔离 {},POSIX find 在这种情况下不会扩展它。

    这是一个适用于大多数 find 实现并解决您的双重扩展问题的单行代码:

    find . -name "*.less" -exec sh -c "plessc \$0 \$(dirname \$0)/\$(basename \$0 less)css" {} \;
    

    在 Solaris 10 及更早版本上,如果 PATH 不符合 POSIX 标准,sh -c 应替换为 ksh -c

    【讨论】:

      【解决方案2】:

      不,不能直接进行。您只能使用{} 直接插入完整的文件名。但是,在 exec 中,您可以输入其他内容,例如 awk。或者您可以通过管道将输出重定向到另一个程序。

      来自findman 页面:

         -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.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-11
        • 2011-08-14
        • 2012-03-10
        • 1970-01-01
        • 2012-11-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多