如何通过比较文件名和文件夹名将文件复制到同名文件夹?

时间:2018-09-27 14:01:04

标签: linux bash shell

我正在尝试比较同一文件夹中的文件和文件夹名称,以将文件复制到具有相同名称的文件夹中。

现在这是我的代码:

测试文件/文件夹名称: sth(文件夹)sth2.fastq sth.fastq

for fname in *.fastq; do
    for f in */; do
        if "${fname%.*}"=="$f"; then
            -exec cp $fname /${f} \;
        fi
    done
done  

运行代码时出现此错误:

./ script.sh:第3行:sth2 == sth /:没有此类文件或目录 ./script.sh:第3行:sth == sth /:没有此类文件或目录

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我们这样说吧:

for fname in *.fastq; do
    #Getting rid of the extension
    locfname=${fname%.*}
    #Getting rid of numbers if any
    locdirname=${locfname//[0-9]*}
    #Creating the directory if it doesn't exist
    if [[ ! -d $locdirname ]]; then
        mkdir $locdirname
    fi
    #Moving file in the proper directory (can use cp instead)
    mv $fname $locdirname
done

希望这会有所帮助

相关问题