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

标签 linux bash unix if-statement nested-loops

我正在尝试将特定文件复制到特定文件夹,但文件名类似于 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 语句,但我一定是错误地构建了它。非常感谢任何帮助。

最佳答案

我认为你的比较 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

关于linux - 试图将特定文件复制到特定文件夹,但有一个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49121264/

相关文章:

php - UTF-8贯穿始终

android -/arm64/Image 到 zImage 或 boot.img

bash - 将交互式命令的输出管道输出到 less

c - 为什么我不能忽略 SIGSEGV 信号?

Unix 查找替换多个文件中的特殊字符

linux - 从 linux bash 命令输出中解析所有列元素

bash - 使用Bash循环删除未分配的Graylog2索引/碎片

linux - 比较文本文件与差异时如何过滤掉/忽略特定行

c - 建议的阅读顺序和其他问题

python - 为什么命令及其参数必须在 subprocess.Popen 的列表中?