在包含n个文件的文件夹中查找多个模式.如果找到匹配的模式,则创建mkdir



我们可以在包含n个文件的文件夹中搜索多个模式吗?如果找到了每个模式的匹配项,则创建一个目录,并将类似模式类型的文件推入相同的目录。

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

我想搜索一个像This code is from的模式。如果在X文件夹的多个文件中发现了一个匹配的字符串,则创建一个名为dir1的目录,并将所有匹配的文件推入dir1

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

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

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

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

我的意思是,这并不优雅,但你可以使用嵌入的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

最新更新