schannall
schannall

Reputation: 5

Copy files in different folders in ther respective folder via shell

I'm trying to copy files in different folders to their own folder:

/Test/Folder1/File1
/Test/Folder2/File2
/Test/Folder3/File3

I want to create a copy of each file in it's own folder:

/Test/Folder1/File1.Copy
/Test/Folder2/File2.Copy
/Test/Folder3/File3.Copy

I would try using

find /SapBackup/server*/SAPDBBAK/*_COM.dump -mmin 360 -type f -execdir cp . {} 

but I don't know how to use the filename and folder of the found files as an operand.

I want to use a one-liner to add it to crontab, so a for-solution would not be suitable (AFAIK)

Thanks for your help

Upvotes: 0

Views: 484

Answers (3)

randomir
randomir

Reputation: 18697

You are on the right track with -execdir action.

Just note you can use {} multiple times, for example:

find /some/path -mmin 360 -type f -execdir cp {} {}.copy \;

or even simpler, combine it with brace expansion1 in bash:

find /some/path -mmin 360 -type f -execdir cp {}{,.copy} \;

1 Brace expansion, as explained in the docs, is a shell expansion by which arbitrary strings may be generated. In fact, you might consider it to be a Cartesian product in bash.

For example: a{b,c} will expand to two words: ab and ac. Namely, set containing word a was "multiplied" with a set containing two words, b and c.

Similarly when used multiple times, e.g. {a,b}{c,d} expands to 4 words: ac, ad, bc and bd (to test, try: echo {a,b}{c,d}).

In cp command above, we used a zero-length word and .copy to (re-)produce the original word and the original word with .copy appended:

$ echo filename{,.copy}
filename filename.copy

Upvotes: 1

Wojciech Marzec
Wojciech Marzec

Reputation: 29

In order to copy directories you have to add -r flag to cp command. What's about a oneliner like following:

find /SapBackup/server*/SAPDBBAK/*_COM.dump -mmin 360 | xargs -I {} cp -r {} {}.copy

Upvotes: 0

A.Villegas
A.Villegas

Reputation: 517

If you put these lines on a bash script, you can call it from the crontab.

for i in $(ls /path/to/folder); do cp $i $i.copy; done

It's a simple code and you can change it so easy.

I hope that's usefull.

Upvotes: 0

Related Questions