bash 从特定文件扩展名在文件夹中创建子目录

bash 从特定文件扩展名在文件夹中创建子目录

bash下面,我尝试从具有特定扩展名的文件在目录内创建子目录.bam。文件.bam被修剪,结果是保存在$RDIR原始文件所在位置或上一级的文件夹名称。可能有多个.bam文件,但它们始终具有相同的格式。我也发表了评论。谢谢 :)。

巴什

DIR=/home/cmccabe/Desktop/folder   ## define data directory path
cd "$DIR" || exit 1  # check directory exists or exit
for RDIR in R_2019* ; do  ## start processing matching "R_2019*" to operate on desired directory and expand
 cd "$RDIR"/BAM   ## change directory to subfolder inside $RDIR
  bam=$(find . -type f -name "*.bam")   # extract .bam
  sample="$(echo $bam|cut -d_ -f3-)" # remove before second underscore
  mkdir -p "${sample%.*}" && mv "$sample" "RDIR"/"${x%.*}"  ## make directory of sample id one level up
done  ## close loop

结构/home/cmccabe/Desktop/folder --- 这是 $DIR ---

R_2019_00_00_00_00_00_xxxx_xx-0000-00  --- this is $RDIR ---
     BAM   ---subdirectory---
       IonCode_0241_19-0000-Last-First.bam.bai
       IonCode_0241_19-0000-Last-First.bam
       IonCode_0243_19-0001-Las-Fir.bam.bai
       IonCode_0243_19-0001-Las-Fir.bam
     QC    ---subdirectory---

在脚本结构之后/home/cmccabe/Desktop/folder --- 这是 $DIR---

R_2019_00_00_00_00_00_xxxx_xx-0000-00  --- this is $RDIR ---
     BAM                  ---subdirectory---
     19-0000-Last-First   ---subdirectory---
     19-0001-Las-Fir      ---subdirectory---
     QC                   ---subdirectory---

设置-x

bash: cd: R_2019*/BAM: No such file or directory
++ find . -type f -name '*.bam'
+ bam=
++ echo
++ cut -d_ -f3-
+ sample=
+ mkdir -p ''
mkdir: cannot create directory ‘’: No such file or directory

答案1

以下行似乎有问题:

 bam=$(find . -type f -name "*.bam")   # extract .bam
 sample="$(echo $bam|cut -d_ -f3-)" # remove before second underscore

修改:

这可以通过一行实现:

i=$(find . -type f -name "*.bam" -print | while read f;do echo "$f" | cut -d_ -f3-;done| cut -f 1 -d '.') ## To take the file names and then cut.

然后添加 for 循环来创建目录:

for x in $i
        do mkdir -p $DIR/$x
        done

最终脚本:

DIR=/home/vvek/MyLearning/Linux/bam/   ## define data directory path
cd "$DIR" || exit 1  # check directory exists or exit
for RDIR in R_2019* ; do  ## start processing matching "R_2019*" to operate on desired directory and expand
 cd "$RDIR"/BAM   ## change directory to subfolder inside $RDIR
i=$(find . -type f -name "*.bam" -print | while read f;do echo "$f" | cut -d_ -f2-;done| cut -f 1 -d '.')  # extract .bam

for x in $i
        do mkdir -p $DIR/$x
        done
done  ## close loop

相关内容