Find, copy, rename within the same directory

2019-08-06 05:49发布

问题:

I an new to bash and could do with some help. I am looking to create a command that will instantly duplicate the last created file with a new new. So far I come up with the following command;

find /home/ian/Desktop/TEST/ -type f -mmin -1 -exec echo cp {} /home/ian/Desktop/TEST/ \;

But for the life or me I cannot find a way to rename the file and I have looked around and tried various methods but none seemed to work. I would like to have control over the renaming so that I can add '_backup' to each file that is copied.

What would be the best way to go about this? Sorry if this is such a basic question

All the best, Ian

回答1:

You probably need to use -execdir instead of -exec:

-execdir command ;

-execdir command {} +
       Like -exec, but the specified command is run from the  subdirec‐
       tory  containing  the  matched  file,  which is not normally the
       directory in which you started find.

The following command seems to work as expected:

find /home/ian/Desktop/TEST/ -type f -mmin -1 -execdir echo cp \{} \{}_backup \;


回答2:

you can make the output of a command a string, like a=$(my_command). (My_command being the find.) Then you can say mv "$a" "$a".backup.



回答3:

find /home/ian/Desktop/TEST/ -type f -mmin -1 -exec echo cp {} /home/ian/Desktop/TEST/{}_backup