I have multiple directories in a single directory.

Astrocytes_BloodCells_GeneSet/   Astrocytes_Polydendrocytes_GeneSet/  Endothelia_Neurons_GeneSet/   Microglia.y_Neurons_GeneSet/           Oligodendrocytes_Microglia.y_GeneSet/      Polydendrocytes_Microglia.x_GeneSet/
Astrocytes_Endothelia_GeneSet/   BloodCells_Endothelia_GeneSet/       Microglia.x_BloodCells_GeneSet/   Oligodendrocytes_Astrocytes_GeneSet/   Oligodendrocytes_Neurons_GeneSet/      Polydendrocytes_Microglia.y_GeneSet/
Astrocytes_Microglia.x_GeneSet/  BloodCells_Microglia.y_GeneSet/      Microglia.x_Endothelia_GeneSet/   Oligodendrocytes_BloodCells_GeneSet/   Oligodendrocytes_Polydendrocytes_GeneSet/  Polydendrocytes_Neurons_GeneSet/

Each of these subdirectories contains a folder that follows the format:


for example, Astrocytes_BloodCells_GeneSet/ contains a folder called _.LD_RESULTS_Astrocytes_BloodCells_GeneSet/, and so on. Inside these directories are multiple .txt files.

I am trying to write a simple script that copies the .txt inside Astrocytes_BloodCells_GeneSet/,Astrocytes_Polydendrocytes_GeneSet/ etc... into the _.LD_RESULTS_directoryname folders. How can I achieve this?

  • Can you provide the output of tree and an example of what you would like the output of tree to look like after the move operation?
    – DopeGhoti
    Dec 20, 2018 at 16:38
  • Did you mean, for the example, to say that the subfolder was _.LD_RESULTS_Astrocytes_BloodCells_GeneSet instead of ...Endothelia...?
    – Jeff Schaller
    Dec 20, 2018 at 16:39
  • That was a typo, corrected.
    – Workhorse
    Dec 20, 2018 at 16:41

2 Answers 2


Assuming that you have a top directory,where you have only these directories, I think the following shellscript can both create the _.LD_RESULTS_ subdirectories if necessary and do to copying.


for i in */
 mkdir -p "$target"
 cp -p "${i}"*.txt "$target"

Are you sure that you want copies? An alternative is to move the files. If you want a backup, it should be in another drive (to survive a drive crash).


If the _.LD_RESULTS directory names contain the parent directory name exactly, then this for loop should do the trick:

for dir in *_*_GeneSet
  echo cp "$dir"/*.txt "$dir"/_.LD_RESULTS_"$dir"/

I used a pattern for the for loop's wildcard that requires "anything", underscore, "anything", underscore, "GeneSet" as the parent directory name. Adjust that to widen or narrow the scope as needed.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .