Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unix mv --backup=numbered

I'm trying in php to move a folder but keep both files in the dest folder if exist duplicate. i tried todo that in recursion but its too complicated so many things can go wrong for example file premissions and duplicate files\folders.

im trying to work with system() command and i cant figure out how to move files but keep backup if duplicate without destroying the extension

$last_line = system('mv --backup=t websites/test/ websites/test2/', $retval);

gives the following if file exist in both dirs:

ajax.html~
ajax.html~1
ajax.html~2

what im looking for is:

ajax~.html
ajax~1.html
ajax~2.html

or any other like (1), (2) ... but without ruining the extension of the file. any ideas? please.

p.s must use the system() command.

like image 301
Mike Avatar asked Mar 20 '13 16:03

Mike


1 Answers

For this problem, I get sed to find and swap those extensions after the fact in this function below (passing my target directory as my argument):

swap_file_extension_and_backup_number ()
{
IFS=$'\n'
for y in $(ls $1)
do
    mv $1/`echo $y | sed 's/ /\\ /g'` $1/`echo "$y" | sed 's/\(\.[^~]\{3\}\)\(\.~[0-9]\{1,2\}~\)$/\2\1/g'`
done
}

The function assumes that your file extensions will be the normal 3 characters long, and this will find backups up to two digits long i.e. .~99~

Explanation:

This part $1/`echo $y | sed 's/ /\\ /g'` $1/`echo "$y" represents the first argument (the original file) of mv but protects you from space characters by adding an escape.

The last part $1/`echo "$y" | sed 's/\(\.[^~]\{3\}\)\(\.~[0-9]\{1,2\}~\)$/\2\1/g' is of course the target file where two parenthetic groups are swapped .i.e. /\2\1/

like image 139
MarkB Avatar answered Sep 28 '22 08:09

MarkB