justaguy
justaguy

Reputation: 3022

move matching files in folder if they match a specific destination folder name

I can not figure out how to move files to a folder if the match part of the name of the folder.

For example, if I have 4 files that the below bash will use a specific file extension and create a folder for:

Bash

for f in /home/cmccabe/Desktop/NGS/API/2-19-2016/*.bam
do
   [ -d "$f" ] && continue
   base=${f%.*}
   mkdir -p "$base"
   mv "$f" "$base/"
done

Before the bash is run:

IonXpress_001.bam
IonXpress_002.bam
IonXpress_003.bam
IonXpress_007.bam

After the bash is run

4 folders are created with each .bam inside of it:

 `Folder`            `File`
IonXpress_001 >>> IonXpress_001.bam
IonXpress_002 >>> IonXpress_002.bam
IonXpress_003 >>> IonXpress_003.bam
IonXpress_007 >>> IonXpress_007.bam

In the folder there is a directory named test that has 4 files in it:

 IonXpress_001_newheader_all_IDT.meterics
 IonXpress_002_newheader_all_IDT.meterics
 IonXpress_003_newheader_all_IDT.meterics
 IonXpress_007_newheader_all_IDT.meterics

I am trying to move the file in the test folder that matches the beginning string into the main folder. The test folder is also moved as a subdirectory with the file in it. I apologize for the lenghty post just trying to provide all the details. Thank you :).

desired result

   `Folder`            `File`           `folder`
IonXpress_001 >>> IonXpress_001.bam   >>> test >>> IonXpress_001_newheader_all_IDT.meterics
IonXpress_002 >>> IonXpress_002.bam   >>> test >>> IonXpress_002_newheader_all_IDT.meterics
IonXpress_003 >>> IonXpress_003.bam   >>> test >>> IonXpress_003_newheader_all_IDT.meterics   
IonXpress_007 >>> IonXpress_007.bam   >>> test >>> IonXpress_007_newheader_all_IDT.meterics

edit

 for f in /home/cmccabe/Desktop/NGS/API/2-19-2016/*.bam
do
 base="${f%.*}"
 mkdir -p "$base"; mkdir -p "$base/"(picard,fastqc,bedtools,30x}
 mv "$f" "$base/"
 mv "picard/fastqc/bedtools/30x/$f"* "$base/picard/fastqc/bedtools/30x"
done

 `Folder`            `File`           `folder`
IonXpress_001 >>> IonXpress_001.bam   >>> picard/fastqc/bedtools/30x >>> IonXpress_001_newheader_all_IDT.meterics
IonXpress_002 >>> IonXpress_002.bam   >>> picard/fastqc/bedtools/30x >>> IonXpress_002_newheader_all_IDT.meterics
IonXpress_003 >>> IonXpress_003.bam   >>> picard/fastqc/bedtools/30x >>> IonXpress_003_newheader_all_IDT.meterics   
IonXpress_007 >>> IonXpress_007.bam   >>> picard/fastqc/bedtools/30x >>> IonXpress_007_newheader_all_IDT.meterics

Upvotes: 2

Views: 436

Answers (1)

anubhava
anubhava

Reputation: 784968

You can modify your existing script like this:

sub='picard/fastqc/bedtools/30x'

for f in /home/cmccabe/Desktop/NGS/API/2-19-2016/*.bam
do
   base="${f%.*}"
   mkdir -p {"$base","$base/$sub"}

   mv "$f" "$base/"
   mv "$sub/$f"* "$base/$sub/"
done

mkdir -p exits silently if destination directory already exists.

Upvotes: 1

Related Questions