我想使用 find 来搜索不同子目录中的文件,这些子目录必须与其父类别匹配相同的模式。
例子:
ls
Random1_fa Random2_fa Random3_fa
在这些目录中有不同的文件,我只想搜索其中一个文件:
cd Random1_fa
Random1.fa
Random1.fastq
Random1_match_genome.fa
Random1_unmatch_genome.fa
...
我只想“查找”带有“文件名”的文件.fa 例如:
/foo/bar/1_Random1/Random1_fa/Random1.fa
/foo/bar/2_Random2/Random2_fa/Random2.fa
/foo/bar/3_Random5/Random5_fa/Random5.fa
/foo/bar/10_Random99/Random99_fa/Random99.fa
我做到了:
ls | sed 's/_fa//' |find -name "*.fa"
但不是我要找的。 我想将 sed 的结果重定向为查找中的正则表达式模式。 一些“类似”的东西:
ls| sed 's/_fa//' |find -name "$1.fa"
或
ls| sed 's/_fa/.fa/' |find -name "$1"
最佳答案
当您可以直接使用 find
执行正则表达式条件时,为什么要使用 sed
从标准输入中读取以过滤掉要排除的文件。首先,您对所有以 _fa
结尾的目录运行 shell glob 扩展,并获取要在 find
表达式中使用的 find
字符串的名称。您需要做的就是
for dir in ./*_fa; do
# Ignore un-expanded globs from the for-loop. The un-expanded string woul fail
# to match the condition for a directory(-d), so we exit the loop in case
# we find no files to match
[ -d "$dir" ] || continue
# The filename from the glob expansion is returned as './name.fa'. Using the
# built-in parameter expansion we remove the './' and '_fa' from the name
str="${dir##./}"
regex="${str%%_fa}"
# We then use 'find' to identify the file as 'name.fa' in the directory
find "$dir" -type f -name "${regex}.fa"
done
以下将匹配仅包含 [A-Za-z0-9]
并以 .fa
结尾的文件名。在包含您的目录的顶层运行此命令以匹配所有文件。
要将文件复制到其他地方,请添加以下内容
find "$dir" -type f -name "${regex}.fa" -exec cp -t /home/destinationPath {} +
关于regex - 使用 find 来识别与父目录名称相同的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54108699/