查找文件存在的所有目录,使文件包含搜索字符串 [英] Find all directories in which a file exists, such that the file contains a search string

查看:29
本文介绍了查找文件存在的所有目录,使文件包含搜索字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个目录树,我需要按如下方式处理:

I have a directory tree that I need to process as follows:

  • 我有一个文件需要复制到选定的几个子目录中
  • 感兴趣的子目录包含一个文件,我可以在其中使用正则表达式匹配已知的搜索字符串

理想情况下,我希望:

  • 对目录中的所有文件执行正则表达式匹配
  • 如果正则表达式匹配,则将文件复制到该目录

问题是我对 ANT 很陌生,我很难找到自己的路.我在文档中找不到关于基于正则表达式搜索的每个目录操作的任何任务.我发现的最接近的是正则表达式替换任务 (<replaceregexp>),它可以跨文件搜索和替换模式.

The trouble is that I am quite new to ANT and I'm having difficulties finding my way around. I can't find any tasks in the docs about per directory operations based on regex search. The closest thing I've found is a regex replace task (<replaceregexp>) that can search and replace patterns across files.

这甚至可能吗?我真的很感激一个开始使用的示例.我很抱歉请求代码 - 我只是不知道如何开始将任务组合在一起来实现这一目标.

Is this even possible? I'd really appreciate a sample to get started with. I apologize for requesting code - I simply don't know how to begin composing the tasks together to achieve this.

或者,我可以选择对每个目录的所有复制操作进行硬编码,但这意味着随着项目的增长手动保持所有内容同步.理想情况下,我想根据我描述的正则表达式搜索/复制方法使其自动化.

Alternatively I have the option of hardcoding all the copy operations per directory, but it would mean manually keeping everything in sync as my project grows. Ideally I'd like to automate it based on the regex search/copy approach I described.

谢谢!

推荐答案

你的要求有点不标准,所以我用自定义的 Groovy 任务.

Your requirement is a bit non-standard, so I've solved it using a custom Groovy task.

这是一个工作示例:

<project name="find-files" default="copy-files">

    <!--
    ======================
    Groovy task dependency
    ======================
    -->
    <path id="build.path">
        <pathelement location="jars/groovy-all-1.8.6.jar"/>
    </path>
    <taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy" classpathref="build.path"/>


    <!--
    =========================
    Search for matching files
    =========================
    -->
    <target name="search-files">
        <fileset id="filesContainingSearchString" dir="src">
            <include name="**/*.txt"/>
            <containsregexp expression="[4-6]\.[0-9]"/>
        </fileset>
    </target>

    <!--
    ===================================
    Copy file into each directory found
    ===================================
    -->
    <target name="copy-files" depends="search-files">
        <groovy>
        project.references.filesContainingSearchString.each { file ->
            def dir = new File(file.toString()).parent

            ant.copy(file:"fileToBeCopied.txt", toDir:dir)
        }
        </groovy>
    </target>

</project>

注意事项:

这篇关于查找文件存在的所有目录,使文件包含搜索字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆