从文件创建目录并移动文件

从文件创建目录并移动文件

我想根据特定模式移动文件。我正在使用这段代码,但它不能很好地完成任务。

for file in *.fastq.gz
do
 dir="${file%R*}"
 mkdir -- "$dir"
 mv -- "$file" "$dir"
done

以下是一些文件示例:

121123_SN323_A_L002_GPS-100_R1.fastq.gz
121123_SN323_A_L002_GPS-100_R2.fastq.gz
130201_SN132_B_L007_GPS-100_R1.fastq.gz
130201_SN132_B_L007_GPS-100_R2.fastq.gz

121123_SN323_A_L002_GPS-104_R1.fastq.gz
121123_SN323_A_L002_GPS-104_R2.fastq.gz
130201_SN132_B_L007_GPS-104_R1.fastq.gz
130201_SN132_B_L007_GPS-104_R2.fastq.gz

因此,对于这些文件,我只想创建两个文件夹,GPS100并且GPS104.但我得到了 4 个带有上面代码的文件夹,即:

121123_SN323_A_L002_GPS-100_
121123_SN323_A_L002_GPS-104_
130201_SN132_B_L007_GPS-100_
130201_SN132_B_L007_GPS-104_

答案1

您还需要剥掉前面的$dirwith dir=GPS${dir#*GPS}

生成的脚本:

$ ls
121123_SN323_A_L002_GPS-100_R1.fastq.gz
121123_SN323_A_L002_GPS-100_R2.fastq.gz
121123_SN323_A_L002_GPS-104_R1.fastq.gz
121123_SN323_A_L002_GPS-104_R2.fastq.gz
130201_SN132_B_L007_GPS-100_R1.fastq.gz
130201_SN132_B_L007_GPS-100_R2.fastq.gz
130201_SN132_B_L007_GPS-104_R1.fastq.gz
130201_SN132_B_L007_GPS-104_R2.fastq.gz

$ for a in *.fastq.gz
do
  dir=${a%_R*}
  dir=GPS${dir#*_GPS}
  mkdir -- "$dir" 2>/dev/null
  mv -i "./$a" "$dir/"
done

$ ls
GPS-100/  GPS-104/

$ ls *
GPS-100:
121123_SN323_A_L002_GPS-100_R1.fastq.gz
121123_SN323_A_L002_GPS-100_R2.fastq.gz
130201_SN132_B_L007_GPS-100_R1.fastq.gz
130201_SN132_B_L007_GPS-100_R2.fastq.gz

GPS-104:
121123_SN323_A_L002_GPS-104_R1.fastq.gz
121123_SN323_A_L002_GPS-104_R2.fastq.gz
130201_SN132_B_L007_GPS-104_R1.fastq.gz
130201_SN132_B_L007_GPS-104_R2.fastq.gz

相关内容