Reputation: 724
I have a text file with a list of file paths.
For example, they generally look like this: F:\datapath\some more path\path\path\thefile.ext
I'm trying to feed it into hobocopy, but hobocopy doesn't like file paths with trailing slashes. So, I'm trying to extract the file's path, then remove the trailing backslash, then echo the command to preview it:
@echo off
FOR /F "tokens=* delims=" %%i in (filelist.txt) do (
ECHO Copy attempt of this file: %%i
FOR %%h IN ("%%i") DO (
REM -- capture the file path
SET filepath=%%~ph
REM -- remove the trailing slash on the path
SET filepath=%filepath:~0,1%
REM -- echo the command to see how it looks
ECHO hobocopy "F:%%~ph" "V:\copy_test%%~ph" "%%~nxh"
)
)
Obviously that code doesn't actually work, but I'm not sure how to proceed from here.
Upvotes: 1
Views: 2740
Reputation: 130819
You were darn close to having a very good solution. You don't need the %%h FOR loop. And your solution will fail if the path or file name contains ! (not likely, but it can happen)
I'm not sure if you will run into any problem if the file is in the root directory. F: and F:\ usually have very different meanings. I did not address this potential problem in the solution below.
@echo off
FOR /F "delims=" %%i in (filelist.txt) do (
ECHO Copy attempt of this file: %%i
REM -- capture file path and file name
SET "filepath=%%~pi"
SET "filename=%%~nxi"
REM -- enable delayed expansion so we can access variable assigned within loop
SETLOCAL enableExtensions enableDelayedExpansion
REM -- remove trailing backslash
set "filepath=!filepath:~0,-1!"
REM perform shadow copy on file
hobocopy "F:!filepath!" "V:\copy_test!filepath!" "!filename!"
REM -- disable delayed expansion so %%i expansion does not corrupt values containing !
ENDLOCAL
)
I think Joop Egen's comment is correct. I believe this one liner may work
@echo off
for /f "delims=" %%i in (filelist.txt) do hobocopy "%%~dp." "V:\copy_test%%~p." "%%~nx"
This very simple solution should not have any problems with a root directory either.
Upvotes: 2
Reputation: 724
I seem to have got it working, though I doubt it's done in the most efficient manner. Is there a better way?
@echo off
SETLOCAL enableextensions enabledelayedexpansion
FOR /F "tokens=* delims=" %%i in (filelist.txt) do (
ECHO Copy attempt of this file: %%i
FOR %%h IN ("%%i") DO (
REM -- capture file path
SET filepath=!filepath!%%~ph
REM -- remote trailing backslash
SET filepath=!filepath:~0,-1!
REM perform shadow copy on file
hobocopy "F:!filepath!" "V:\copy_test!filepath!" "%%~nxh"
REM clear variable
SET filepath=
)
)
Upvotes: 1