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

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

问题描述

我有一个目录树,需要按以下步骤处理:

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

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

理想情况下,我想:

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

问题在于我对ANT还是很陌生,很难找到自己的出路.我找不到基于正则表达式搜索的有关按目录操作的文档中的任何任务.我找到的最接近的东西是一个regex替换任务(< 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.

谢谢!

推荐答案

您的要求有点不规范,因此我使用自定义

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>

注释:

  • Groovy jar can be downloaded from Maven Central

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

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