简体   繁体   English

如何删除目录中的文件没有特定正则表达式匹配的目录?

[英]How to delete directories where files within directories don't have a certain regex match?

Say I have the following directories:假设我有以下目录:

dir > subdir1 > k.txt > "Keep please"
    > subdir2 > l.txt > "Keep me"
    > subdir3 > m.txt > "Delete me"
    > subdir4 > n.txt > "remove"

I want to find an expression that will let me do a regex match on the contents within the file, and delete the subdirectories that do not have that string match.我想找到一个表达式,让我对文件中的内容进行正则表达式匹配,并删除没有该字符串匹配的子目录。 So in the example above, I would use something like grep -r "Keep.* for the files and them only rm subdir3. I want to end up with:因此,在上面的示例中,我将使用grep -r "Keep.*之类的文件,并且它们只有rm subdir3。我想结束:

dir > subdir1 > k.txt > "Keep please"
    > subdir2 > l.txt > "Keep me"

Here is a shell script approach:-这是一个 shell 脚本方法:-

#!/bin/ksh

for dir in <your directory name here>/*
do
        printf "Checking dir: ${dir}..."
        if grep -q "Keep" ${dir}/*
        then
                print " [Keep]"
                # do nothing
        else
                print " [Remove]"
                # rm -rf ${dir}
        fi
done

I commented rm statement, you can first run the script and carefully verify the print statement output to make sure it is picking the right directory names.我注释了rm语句,您可以先运行脚本并仔细验证print语句 output 以确保它选择了正确的目录名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用setfacl的新文件和目录没有相同的权限 - New files and directories don't have same permission using setfacl 如何搜索目录并找到与正则表达式匹配的文件? - How do i search directories and find files that match regex? 如何使用find + regex匹配文件并仅返回包含所述文件的唯一目录? - How to use find + regex to match files and return only unique directories containing said files? 如何压缩不符合特定条件的文件? - How do I zip files that don't match certain criteria? 如何在Linux中查找并删除名称不匹配的目录? !#重击 - How to find in linux and delete directories that not match a name? !#Bash 如何删除目录中的前 50 个目录 linux bash - how to delete first 50 directories within a directory linux bash 如何从多个目录中提取多个文件,而不同目录中的不同文件可能具有相同的名称 - how to scp multiple files from multiple directories, while different files in different directories may have the same name 如何检查和删除python中两个不同目录中不相同的文件? - How to check and delete files that are not same in two different directories in python? 如何使用单个命令删除linux中不同目录中的文件 - How to delete files in different directories in linux with a single command 如何从目录中删除名称奇怪的文件? - How can I delete files with odd names from directories?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM