Files

從文件創建目錄並移動文件

  • July 2, 2016

我想根據特定模式移動文件。我正在使用此程式碼,但它不適用於該任務。

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

所以有了這些文件,我只想創建兩個文件夾,GPS100GPS104. 但是我用上面的程式碼得到了 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_

您還需要剝離$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

引用自:https://unix.stackexchange.com/questions/293378