3

I have multiple files (all with the same extention) in different subfolders and I want to copy only a subset of them. For example, consider:

A/: 1.txt, 2.txt, 3.txt
B/: 4.txt, 5.txt, 6.txt
C/: 7.txt, 8.txt, 9.txt

I want to copy files 1.txt, 2.txt, 5.txt, and 8.txt to a new folder.

Is there a way to automate this operation knowing that I have more than 500 subfolders each containing a few thousand files and a list (txt file) of the files I want to copy?

2

If the list contains complete paths, you can move them in a loop:

while read file ; do
   mv "$file" dir/
done < list.txt

If the list contains only file names, without paths, you can use globstar.

# enable double asterisk to recurse directories
shopt -s globstar

while read file ; do
   mv **/"$file" dir/
done < list.txt
  • Thanks, It seems to be working on a small trial set. I had to modify it a little to go through all the subfolders. I'll update you once i run it on the main set – Bessem Jun 3 at 16:02
0

So I tweaked the central command in order to go through the subfolders

while read file ; do
   mv dir1/*/"$file" dir2/
done < list.txt

Thanks

  • It's a minor tweak that depends on the contents of your input list. Another option is to use globstar to recurse directories. I have edited my answer to demonstrate. – xiota Jun 5 at 20:37

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.