Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

find specific files and copy to new folder

I am trying to find all txt files in mutiple directories and use the contents of file to match each txt file and copy them to a new directory (all). Not every directory will have a match
and there are more then txt files inside each, but those are not needed. The below executes but no files are copied. Thank you :).

dir

123456789000
  123456789000_00a.txt
  123456789000_00b.txt
  123456789000_04a.txt
  123456789000_04b.txt
  123456789000_05a.txt
  123456789000_05b.txt
123456789111
  123456789111_00a.txt
  123456789111_00b.txt
123456789222
  123456789222_00a.txt
  123456789222_00b.txt

file

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

123456789000_00
123456789000_04
123456789111_00

desired all

123456789000_00a.txt
123456789000_00b.txt
123456789000_04a.txt
123456789000_04b.txt

bash

for a in *; do  # loop and read into a
  [ -d "$a" ] || continue # ensure a is directory
    cd "$a" ## descend into each $a
     find . -type f -name "*.txt" -exec cp {} ${dest} \; # find txt file in directory and use file to match
    cd ..  ## go one directory back
done  <file  ## close loop

>Solution :

Your sample code doesn’t actually use the content of file at all, it’s looping over a glob (presumably matching your directories), changing into each directory and attempting to grab all txt files. You also have a syntax error in $(dest} which may be why nothing gets copied.

This is closer to what you described:

while IFS= read -r line ; do
  find -type f -name "${line}*txt" -exec cp {} "${dest}" \; 
done < file
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading