0

I have a txt file that include only the names of files that are in different sub-folders, I'm trying to write a function that will find this files and copy them to specific folder.

This is an example of my dir:

1
├── 2
│   ├── a.txt
│   ├── b.txt
│   └── c.txt
│  
└── 3
    ├── d.txt 
    └── e.txt

This is an example of files_name.txt file:

a.txt
c.txt
e.txt

I tried this function I found those files but I couldn't copy them.

xargs -d '\n' -a files_name.txt -I FILENAME find 1 -type f -name FILENAME -exec cp {} DESTINATION_FOLDER: \;

1 Answer 1

1

I don't know a lot about xargs, but the following should loop over your text file and copy the file into the destination folder one by one.

while read p; do
    find 1 -name "$p" -exec bash -c 'cp "$1" DESTINATION_FOLDER' _ {} \;
done < files_name.txt
2
  • Looks good - but is the bash subshell really necessary? wouldn't -exec cp {} DESTINATION_FOLDER \; or -exec cp -t DESTINATION_FOLDER {} \; work just as well? Oct 25, 2019 at 23:29
  • Don't see why not. Guess I'm just used to using the subshell form like this... I think security problems arise when you do -exec sh -c 'echo {}'\;, for example, so that's something to watch for
    – reas0n
    Oct 28, 2019 at 15:47

You must log in to answer this question.

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