1

I am trying to copy specific subdirectories (and the files contained in them) to a new directory. Assuming I am in the first directory (dir0/), this contains a number of subdirectories named 000/, 001/, 002/, ... and so on. Each of these subdirectories contains 1000 sub-subdirectories, with files inside them. One example could be: dir0/000/aaa/file1.txt or dir0/001/bbb/file2.txt.

I have a .txt file containing a list of the subdirectories to copy (I only have the name of the subdirectories, not the full path), so, for the example above, my txt file will contain this information:

aaa
bbb

Is there a way to copy all the subdirectories whose names are included in the txt file to a new directory using bash or python?

Thank you for your help. I am new to both bash and python.

2
  • What should happen if you have dir0/000/aaa/ and also dir0/018/aaa/? Or can you be 100% sure that all the names in your text file will be unique? – terdon May 20 '20 at 17:33
  • the names in the text files are unique – ginopino May 20 '20 at 17:35
1

Assuming that, as you said in the comments, the names in the text file are unique, that there will only be one subdirectory with that name in the entire directory tree, then you can simply do (in bash):

while read -r dirName; do
    cp -r dir0/*/"$dirName"/ /path/to/newTargetDir
done < listOfDirs.txt
1
  • That worked perfectly! Thank you so much! – ginopino May 20 '20 at 18:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.