尝试将特定文件复制到特定文件夹,但有一个问题

问题描述 投票:0回答:4

我正在尝试将特定文件复制到特定文件夹,但文件名如Long_John_SilverMiss_HavishamMaster_Pip,文件夹名称类似于LongMissMaster。所以基本上我正在尝试将文件复制到各自的文件夹,例如Master_Pip.txt进入名为Master的文件夹。所以我试图捕获文件名的第一个单词并以某种方式使用它作为参考,但是,在这一点上,我摇摇欲坠。

for fldr in /home/playground/genomes* ; do

find . -name *fna.gz | while read f ; do

    f_name=$( echo $fldr | cut -d '/' -f 7 | cut -d '_' -f 1) ;

    #echo $f_name ;

    if [ "$f_name" == /home/playground/port/"$f_name" ]; then

        cp -r "$f" /home/playground/port/"$f_name"/ ;

    else

        continue    

    fi

done

done

编辑 - - - - - - - - - - - - - - - - - - - - - - - -

for fldr in /home/p995824/scripts/playground/genomes_2/* ; do

find . -name *fna.gz | while read f ; do

    basenm=${fldr##*/} ; f_name=${basenm%%_*} ; 


    cp -r $f /home/p995824/scripts/playground/port/$f_name/ ;

done

done

此脚本将所有文件复制到所有文件夹。但我正在努力构建一个条件语句,该语句将特定于每个文件被复制到哪个文件夹。我已经尝试了if语句,但我必须错误地构造它。任何帮助深表感谢。

linux bash unix if-statement nested-loops
4个回答
0
投票

我认为你的比较if [ "$f_name" == /home/playground/port/"$f_name" ]是不正确的。 $f_name是文件名的前缀,您将其与完整路径进行比较。

试试这个:

for fldr in /home/playground/genomes* ; do

find . -name *fna.gz | while read f ; do

    # basename will truncate the path leaving only the filename
    f_name=$( basename ${fldr} | cut -d'_' -f1) ;

    # $f_name is the filename prefix "Long", "Master", etc

    # if the directory exists (-d)
    if [ -d "/home/playground/port/$f_name" ]; then

        # I don't think you need (-r) here if you're just copying a single file
        cp "$f" "/home/playground/port/$f_name/" ;

    else

        continue    

    fi

done

done

0
投票

这是一个可能的解决方案:

for fldr in  `find /tmp/playground/  -type f` 
do 
    NAME=`basename $fldr | cut -d_ -f1`
    DEST=/tmp/playground/$NAME
    if [ -d "$DEST" ]  
    then
        cp $fldr $DEST
    fi 
done

0
投票

也许你可以从另一个方向做?搜索与文件夹名称匹配的文件并复制它们,而不是从文件名的第一个单词中搜索文件夹。我可能错了.. :)

for folder_name in /home/playground/port/*
do
    cp /home/playground/folder_name* $folder_name
done

0
投票

我意识到我是根据文件类型将所有文件复制到所有文件夹中,即.fna.gz,所以我指定了我想要读取的fna.gz文件的类型然后复制。由于通过参数扩展隐含了特异性,因此不需要if语句。它现在完美无缺。

for fldr in /home/scripts/playground/genomes_2/* ; do

basenm=${fldr##*/} ; f_name=${basenm%%_*} ; 

find . -name $f_name*fna.gz | while read f ; do

    cp -r $f /home/scripts/playground/port/$f_name/ ;



done

done
© www.soinside.com 2019 - 2024. All rights reserved.