Reputation: 119
The idea behind this question is simple but I'm new to batch scripts so the nuances are making it impossible for me. I need to create a set of symlinks to replicate the contents of several source directories, which share a common parent directory, into a target directory. Example:
SrcDirParent
SrcDirA
FileA
SrcDirB
FileB
SubDir
FileC
Which using symlinks should create:
DstDir
FileA ~
FileB ~
SubDir
FileC ~
Using ~ to show a symbolic link. SrcDirParent and DstDir are read as absolute paths from an external file. I don't know what files/folders will be in SrcDirParent, and some of the relevant directories might already exist in DstDir while others do not. If they do exist, I need to merge the symlinks with the existing content.
The barrier that I'm currently hitting is with th filepaths. I planned to use two for loops like this:
for /d %%M in (%SRC%\*) do (
for /r %%F in (%SRC%\%%M\*) do (
mklink %DST%\%%F %SRC%\%%M\%%F
)
)
But this requires relative filepaths for %%M and %%F and these variables are being filled with absolute paths. I'm not sure how to fix that.
Another issue that I'm anticipating is when the SRC and DST have conflicting filepaths - I don't want to overwrite existing paths with symlinks.
Hope this was the right place to post this. Thanks in advance.
Upvotes: 0
Views: 193
Reputation: 119
After much trial and error, I found a solution:
setlocal ENABLEDELAYEDEXPANSION
for /d %%M in (%SRC%\*) do (
pushd %%M
for /r %%F in (*) do (
set temp1=%%F
set temp2=!temp1:%%M=!
set temp3=!temp2:%%~nxF=!
if not exist "%DST%!temp3!" (
mkdir "%DST%!temp3!"
)
mklink "%DST%!temp2!" %%F
)
popd %%M
)
It uses "pushd" and "popd" to change the directory for the inner loop, "!string:find=replace!" for modifying the directory names, "exist" to check for existing folders before creating a new one, and "EnableDelayedExpansion" to make all the string operations work correctly. Assumes you have SRC and DST variables set already.
Upvotes: 0