首页 > 解决方案 > 如何匹配来自两个目录的部分匹配文件名并在找到的内容上执行命令

问题描述

我正在尝试匹配两个目录,如果该文件存在于第二个目录中,我想将文件从第一个目录移动到第三个目录。

文件名不完全匹配,它们在名称末尾有一个“_ica”和一个不同的扩展名。

我试图编写一个循环遍历 dir1 的脚本,检查它是否在 dir2 中,如果找到则移动到 dir3:

DATA= /home/eegfilesonlyWM/*
PROCESSED= /home/eegfilesonlyWM/icaddata/*

DONE= /home/eegfilesonlyWM/done/

for f in $DATA ; do 
  fname=${f##*/}
  fname=${fname%/}

 find /home/eegfilesonlyWM/icaddata/ -iname  "${fname*_ica*}" -type f -exec mv {} ./done \; 

done 

我想从第一个目录复制那些在第二个目录中已经有相应文件的文件。

感谢您的任何帮助

标签: linuxbash

解决方案


也许这会做你想要的:

#!/usr/bin/env bash

#Directory paths here
DATA=./DATA
PROCESSED=./PROCESSED 
DONE=./DONE

#Do the test and copy here
for f in `ls -1 $DATA`; do
    #build output name
    p="$PROCESSED/${f/\.xxx/}";    #xxx is the file extension of original
    p="${p}_ica.yyy";              #yyy is the file extension of the processed
    if [ -f  $p ] ; then           
        cp $DATA/$f $DONE
    fi
done

推荐阅读