【问题标题】:Grep for multiple patterns in a folder containing n number of files.And if a match found for patterns create mkdirGrep 在包含 n 个文件的文件夹中查找多个模式。如果找到匹配的模式,则创建 mkdir
【发布时间】:2017-03-11 22:50:52
【问题描述】:

我们能否在包含 n 个文件的文件夹中 grep 查找多个模式。如果为每个模式找到匹配项,则创建一个目录并将相似模式类型的文件推送到同一个目录中。

例如:我有一个文件夹名称:X。 X 里面可以有多个子文件夹和多个文件。

我想搜索像This code is from 这样的模式。如果在X 文件夹中的多个文件中找到此字符串的匹配项,则创建一个名为dir1 的目录并将所有匹配的文件推送到dir1。

如果找到匹配项,其他模式匹配也是如此,创建目录并将文件推送到相应目录。

我尝试使用 grep 搜索可以找到所有模式匹配的文件,但并行我不能做到 mkdir 。这样,对于X n 目录中的 n 个模式匹配,它应该创建。搜索很好,但在并行创建目录时遇到问题。

【问题讨论】:

  • 好的,这是部分 mkdir dir;grep -irl "Version" | xargs cp -t dir/ 我可以创建一个目录并推送与此处的文本匹配的所有文件 iam 收到类似 cp: will not overwrite just-create 之类的错误。在我的情况下,我希望在该目录中复制与文件相同的文件夹结构。

标签: regex linux bash python-2.7 scripting


【解决方案1】:

不幸的是,获得相同文件夹结构的一种方法是不使用xargs cp -t dir,而是使用 rsync 逐一复制,例如,

grep -irl "Version" | xargs -I{} rsync -a "{}" "dir/{}"

【讨论】:

    【解决方案2】:

    我的意思是,它并不优雅,但您可以使用带有搜索字符串数组的嵌入式 for 循环。

    编辑:错过了关于不同匹配字符串的单独文件夹的部分。变化如下。

    #!/bin/bash
    #Assuming:
    #patarr is an array containing all paterns
    #test/files is the location of files to be searched
    #test/found is the location of matching files
    
    for file in test/files/* #*/
    #This loop runs for every file in test/files/. $file holds the filename of the current file
    do
        for ((i=0;i<${#patarr[@]};i++))
        #This loop runs once for every index in the patarr array. $i holds the current loop number
        do
            if [[ $(cat $file | grep ${patarr[$i]} | wc -l) -gt 0 ]]
            #if grep finds at least one match using the pattern in patarr with index "i"
            then
                #cp $file temp/found/ #Old code, see edit above
                mkdir -p temp/found/${pararr[$i]}
                #Makes a folder with the name as our search string. -p means no error if the folder already exists.
                cp $file temp/found/${pararr[$i]}/
                #Copies the file into said folder
            fi
        done
    done
    

    【讨论】:

      猜你喜欢
      • 2018-02-11
      • 2015-02-25
      • 1970-01-01
      • 1970-01-01
      • 2019-09-25
      • 2021-10-01
      • 2012-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多