ap123
ap123

Reputation: 31

recursively copy files(with same name) to one folder

I have a bunch of files in separate folders, that have the same name.

For example,

/path/to/your/directory/1/results.pdf
/path/to/your/directory/2/results.pdf

But, I would like to copy them to the one directory:

/path/to/your/directory/results/

so I have:

/path/to/your/directory/results/results-1.pdf 
/path/to/your/directory/results/results-2.pdf  

etc

The trouble being that the scripts I write, the files will overwrite each other.

Thanks

Upvotes: 0

Views: 2038

Answers (3)

l0b0
l0b0

Reputation: 58778

To rename the files in place as result-0001.pdf, result-0002.pdf etc., so you can move them without any problems:

rename --no-act --verbose 's/.*/sprintf "result-%04d.pdf", ++$main::Mad/e' /path/to/your/directory/results/*/result.pdf

Remove --no-act if you're happy with the result.

Upvotes: 0

Vijay
Vijay

Reputation: 67211

I do this regularly

#!/usr/bin/sh

for i in `find <source_dir_path> -type f`
do
new=`echo $i|nawk -F"/" '{split($NF,a,".");print "<target_dir_path>"a[1]"_"$(NF-1)"."a[2]}'`
cp $i $new
done

Upvotes: 1

abasu
abasu

Reputation: 2524

perhaps something like this will help you find . -type f -exec sh -c 'if [ ! -e ../aaa/{} ]; then cp {} ../aaa/;else i=0; while [ -e ../aaa/{}_${i} ]; do ((i++)); done; cp {} ../aaa/{}_${i}; fi' \;

So basically it searches from a current dir, and for any file, it will copy to ../aaa/ dir, if there is already any such file exists, it will append _0 or _1 or ... whichever makes it uniq, ideally it should be written in a script and find -exec should call for the script if any further refinement is needed, but i think this one liner should be enough

Upvotes: 0

Related Questions