How do I copy files recursively, rename them, but keep the same extension in Bash?
I have a folder with tens of thousands of different file types. I'd like to copy them all to a new folder (Copy1), but also rename them all to $ RANDOM, but keep the extension intact. I understand that I can write a line defining which extension to find and how to name it, but there is a way to do it dynamically because there are at least 100 file types and there may be more in the future.
I have the following:
find ./ -name '*.*' -type f -exec bash -c 'cp "$1" "${1/\/123_//_$RANDOM}"' -- {} \;
but this puts a random number after the expansion and also puts everything in the same folder. I cannot figure out how to do the following 2 things:
1 - Keep all paths intact, but in a new root folder (Copy1)
2 - How to have the name $ RANDOM.extension and not .extension. $ RANDOM
PS - on $ RANDOM, i stands for the actual randomly generated number. I'm interested in preserving the folder structure, so we are dealing with several hundred files in most directories, but all directories / files need to be renamed to $ RANDOM. Another way to look at what I need to do. Copy all content or folder 1 with all subdirectories and files to Folder2 (where Fodler2 is the RANDOM name), then rename all folders and files to random names, but keep all extensions.
EDIT: Ok I figured out how to rename and keep the extension. But I have a problem where it dumps all files to the root directory where the script is being executed. How do I save them to their respective folders? Using Im command:
find ./ -name '*.*' -type f -exec bash -c 'mv "$1" $RANDOM.${1##*.}' -- {} \;
Thank!
source to share
This is what I came up with:
i=1
random="whatever"
find . -name "*.*" -type f | while read f
do
newbase=${f/*./$random$i.} //added counter to filename
cp $f /Path/Name/"$newbase"
((i++))
done
I had to add a counter to random (i), otherwise if the extensions are similar, your files will be overwritten when copied.
In your new folder, your files should look like this:
whatever1.txt
whatever2.txt
etc etc
Hope this is what you were looking for.
source to share
Ok, I figured out how to rename and keep the extension. But I have a problem where its dumping all files to the root directory where the script is being executed. How can I keep them in my folders? Using Im command:
find ./ -name '*.*' -type f -exec bash -c 'mv "$1" $RANDOM.${1##*.}' -- {} \;
Change your command to:
PATH=/bin:/usr/bin find . -name '*.*' -type f -execdir bash -c 'mv "$1" $RANDOM.${1##*.}' -- {} \;
source to share