How to pass a spaced path directory to robocopy?
I need to transfer some files in huge amount using robocopy. Usually, I will transform the directory (from path with spaces to non-spaces) then use robocopy.
But now, I can not do that due to privilege & efficiency.
The flow is simple : read filename from txt and copy.
I had looking and try many things and seems going nowhere.
#echo off
set src_folder=C:\foo bar\lorem ipsum\
set dst_folder=C:\Users\asd\Desktop\copyFileImageFromMagentoFolder\photo_temp20\
for /f "tokens=*" %%i in (list.txt) do robocopy %src_folder% %dst_folder% %%i
Pause
This code work flawlessly if there is no spaces on path directory.
And i tired to modify my code. Add some syntax :
#echo off
set src_folder=C:\foo bar\lorem ipsum\
set dst_folder=C:\Users\asd\Desktop\copyFileImageFromMagentoFolder\photo_temp20\
for /f "tokens=*" %%i in (list.txt) do robocopy "%src_folder%\%%i" "%dst_folder%\%%i"
Pause
But, robocopy throw me error 123 and error 2 (as i remember).
As a note, the folder and file is exist. So please never ask me that question.
Any suggestion will be appreciate
did you try double quotes around the path with spaces?
set src_folder="C:\foo bar\lorem ipsum\"
Related
I have the following in a batch file
for /f "delims=" %%a in ("C:\Program Files (x86)\Wowza\creds.txt") do set %%a
net use J: https://csv/dav %p% /user:%u% /persistent:yes
I get an error:
Environment variable C:\Program Files (x86)\Wowza\creds.txt not defined
What do I need to resolve this?
Secondly, it works for all colleagues apart from one. Same laptop make, model and build. I used my details and it failed on his but worked on mine.
What fails is that it asks for the credentials to map the drive instead of taking them from the file
creds.txt
u:JoeBloggs
p:Password1234
Any idea?
Thanks
the reason for your errormessage is, your for /f loop doesn't evaluate the contents of the file. It takes a quoted string as string not as filename. Usebackq changes that behaviour.
You have another failure in your script: With your code, set %%a translates to set u:JoeBloggs, which is invalid syntax. Correct syntax requrires set u=Joebloggs. Therefore you have to split the line in a part before the colon and a part after the colon and build your set command accordingly (just set %%a would work, when the contents of the file would look like u=JoeBloggs)
Change your for loop to:
for /f "usebackq tokens=1,* delims=:" %%a in ("C:\Program Files (x86)\Wowza\creds.txt") do set "%%a=%%b"
I was going to post a similar answer to #stephan but he beat me to it. If however you have the option to change your creds.txt file to the below:
u=JoeBloggs
p=Password1234
You can shorten the for loop a bit to this:
for /f "usebackq delims=" %%a in ("C:\Program Files (x86)\Wowza\creds.txt") do set "%%~a"
which effectively just does this:
set "u=JoeBloggs"
set "p=Password1234"
I have a for loop that I am trying to get date/time creation information for.
The simple version of my code looks like this:
set home=C:\Temp\dir1
for /f "tokens=*" %%a in ('dir /b %home%\2nd_dir') do echo file info=%%~na %%~ta
It turns out this works if I do not include a path to a directory in the dir function.
i.e. If I run that from the current directory, I get the name and timestamp.
However, if I put in a directory to search for, I am only getting the name. I have tried every single for modifier, and ~t and ~z are the only ones that are not working.
I could use the forfiles function to do this also, but the problem is that directory is actually a network path and not on the C: drive, so I have to robocopy the files from my network path to a local drive to use forfiles (mapping a drive using net use or pushd will greatly complicate things).
I can test this from the command prompt easier.
Does Work
for /f %c in ('dir /b') do set ftime=%~tc
Doesn't work
for /f %c in ('dir /b C:\temp\dir1') do set ftime=%~tc
Does work
for /f %c in ('dir /b C:\temp\dir1') do set fname=%~nc
Anyone know what is going on here?
dir/b gets the filename only, so adding a modifier looks into the current directory for the filename.
Try
pushd yourrequireddirectory
for ...
popd
which should return your appropriate results (no doubt except ~d and ~p)
I've been trying to tackle this problem for few days now to no avail. I have no programming experience whatsoever and this task has been driving me nuts.
I have a txt file that has a list of paths to files that need to be copied. Some 8000 paths are in this file.
Copying each item isn't such a big deal as I can just add the copy command and destination before/after each path.
The crux of my issue is that many of these files have the same filename and when they're in different directories it's not a problem.
However I need all the files in the same destination folder and it keeps overwriting itself.
To sum up, I have a .txt file that basically looks like this:
D:\Big folder\Folder\Subfolder a\filea.file
D:\Big folder\Folder3\Subfolder za\filek.file
D:\Big folder\Folder\Subfolder ds\filed.file
D:\Big folder8\Folder\Subfolder p\filea.file...
I need some tool that will let me copy all of these files into one destination folder, and make sure any duplicates get renamed so that they aren't overwritten.
such that filea.file and filea.file become filea.file and filea1.file
EDIT: so far I've come up with
FOR /F "tokens=* usebackq" %i IN (`type "C:\Users\username\Desktop\completelist.txt"`) DO COPY "%i" "E:\destination\"
which does the read and copy job but not the rename part
Save script below to Copy.bat, open Cmd Prompt from the script directory, and run the bat. It works well for me. Post exact errors, if any.
#echo off
setlocal enabledelayedexpansion
set file=%userprofile%\Desktop\completelist.txt
set "dest=E:\destination" & set "i=" & pushd !dest!
for /f "usebackq tokens=*" %%G in ("%file%") do (
call :rename %%~nG %%~xG %%G
copy "%%G" "%dest%\!target!" >nul )
popd
exit /b
:rename
set "target=%1!i!%2"
:loop
set /a i+=1
if exist "!target!" set "target=%1!i!%2" & goto :loop
set "i=" & echo Copied %3 to !target!
exit /b
I'm trying to rename .jpg files which is in one of many subdirectories of e:\study\pubpmc\test\extracted.
I want to rename files to LastFolderName_ImageName.jpg.
(For example if Figure1.jpg is in e:\study\pubpmc\test\extracted\folder1
I want it to be renamed like this: folder1_Figure1.jpg)
So I need to take out the last folder name from the file's path.
Since it's my first time with batch scripting, I'm having a hard time.
I googled and made code similar to it
but it doesn't seem to work out.
Can you help me with it and tell me where I've done wrong?
Thank you! :)
#echo off
cd /D "e:\study\pubpmc\test\extracted"
for /r %%f in (*.jpg) do (
set mydir=%%~dpf
set mydir=%mydir:\=;%
for /f "tokens=* delims=;" %%i in (%mydir%) do call :LAST_FOLDER %%i
goto :EOF
:LAST_FOLDER
if "%1"=="" (
#echo %LAST%
goto :EOF
)
set LAST=%1
SHIFT
goto :LAST_FOLDER
)
JosefZ explains the obvious problems with your code, but he failed to point out a subtle problem, though his code fixed it:
FOR /R (as well as the simple FOR) begin iterating immediately, before it has finished scanning the disk drive. It is possible for the loop to reiterate the already named file! This would cause it to be renamed twice, giving the wrong result. The solution is to use FOR /F with command 'DIR /B', because FOR /F always processes the command to completion before iterating.
JosefZ also provides code that works for most situations. But there is a much simpler solution that works always:
#echo off
for /f "delims=" %%A in (
'dir /b /s /a-d "e:\study\pubpmc\test\extracted\*.jpg"'
) do for %%B in ("%%A\..") do ren "%%A" "%%~nxB_%%~nxA"
The "%%A\.." treats the file name as a folder and walks up to the parent folder. So %%~nxB gives the name of the parent folder.
The command could be run as a long one liner, directly from the command line (no batch):
for /f "delims=" %A in ('dir /b /s /a-d "e:\study\pubpmc\test\extracted\*.jpg"') do #for %B in ("%A\..") do #ren "%A" "%~nxB_%~nxA"
Avoid using :label and :: label-like comment inside (command block in parentheses). Using any of them within parentheses - including FOR and IF commands - will break their context.
Using variables inside (command block in parentheses). Read EnableDelayedExpansion: Delayed Expansion will cause variables to be expanded at execution time rather than at parse time [and CLI parses all the (command block in parentheses) at once]
Next script should work for you. Note rename statement is merely echoed for debugging purposes.
#ECHO OFF >NUL
SETLOCAL enableextensions disabledelayedexpansion
set "fromFolder=e:\study\pubpmc\test\extracted"
rem my debug setting set "fromFolder=D:\path"
for /F "tokens=*" %%f in ('dir /B /S /A:D "%fromFolder%\*.*"') do (
set "mydir=%%~ff"
set "last=%%~nxf"
call :renameJPG
)
#ENDLOCAL
goto :eof
:renameJPG
rem echo "%mydir%" "%last%"
for /f "tokens=*" %%i in ('dir /B /A:-D "%mydir%\*.jpg" 2^>nul') do (
echo ren "%mydir%\%%~nxi" "%last%_%%~nxi"
)
goto :eof
Resources:
SETLOCAL, disableDelayedExpansion, ENDLOCAL etc.
An A-Z Index of the Windows CMD command line
Windows CMD Shell Command Line Syntax
I already wrote a function for that. You give it any path and it returns you only it's filename or pathname. Works for any path: Url, Windows path, Linux path, etc...
Copy this function at the end of your batch script: (Instructions below)
rem ===========================================================================
:Name_From_Path
SetLocal
set _TMP_FOLDERNAME=%1
for %%g in ("%_TMP_FOLDERNAME%") do set _TMP_FOLDERNAME=%%~nxg
EndLocal & set _Name_From_Path=%_TMP_FOLDERNAME%
goto :EOF
rem ===========================================================================
Usage:
CALL :Name_Of_Path e:\study\pubpmc\test\extracted\folder1
ECHO %_Name_From_Path%
Result: folder1
If your program or com file traverses these folders when renaming, then it should be able to get the present working directory ( path ), pwd. You may be able to chop everything but the LAST_FOLDER out of this by also creating a PREVIOUS_FOLDER and doing a string replacement.
Or you may be able to break the folder names at the '\' token from the pwd into an array and use a -1 array reference to get the last folder name.
In any circumstance you'll want to check for a present working directory command.
If your creating a large text list of all these and issuing a single call to the batch file.
Then you may be better off with something like:
(Symmantic code warning )
(copy) /folderbase/some_folder/oneormore1/image_from_oneormore1.jpg (to) /folderbase/some_folder/oneormore1/oneormore1_image_from_oneormore1.jpg
Instead of copy, window uses rename, linux uses mv.
The latter example would require simply creating a duplicate list and replacing the \ with a _ while parsing through the tokens.
The code you've given is difficult to make sense of, so its hard to discern if you can simple concatenate the current folder and image name (stringify) and then write or rename them where they are.
I'm trying to get only one directory name out of a known path while searching for certain file types. In the example below I am searching for mp4 video files then I want to convert them and move them into a subdirectory of the same name in a different parent directory. The path is known up until the file's direct parent directory, so I was trying to remove the known part of the path. This is giving me a lot of trouble though. In the example below, the variable newDir is empty after the set command and it shows only an input of ~13 with #echo on. Can anyone tell me what I'm doing wrong?
Example:
setlocal enabledelayedexpansion
FOR /R %%X in ("*.mp4") DO (
set currDir="%%~pX" &REM "\test1\test2\dir1"
set newDir=%currDir:~13% &REM dir1
mkdir "C:\new\%newDir%" &REM suppose to be "C:\new\dir1", mine is just "C:\new\"
REM convert mp4 here
cp %%X "C:\new\%newDir%" &REM copies the file
)
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
FOR /R "%sourcedir%" %%a IN (*.mp4) DO (
FOR %%m IN ("%%~dpa.") DO ECHO(XCOPY "%%a" "c:\new\%%~nm\"
)
GOTO :EOF
You would need to change the setting of sourcedir to suit your circumstances.
The required XCOPY commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(XCOPY to XCOPY to actually copy the files.
I note that you're using a very cygwinnish cp in place of copy. Be careful of nameclashes. I changed the command to xcopy in order that the destination directory can be automatically generated if required. Note that you haven't said what you want to do if the destination file already exists.
Here's a trial run on my test directory:
XCOPY "U:\sourcedir\misc\90s\ACDC - Back in Black.mp4" "c:\new\90s\"
XCOPY "U:\sourcedir\misc\90s\extended\Kelly Rowland - Wor! (Freemasons Arabic Mix).mp4" "c:\new\extended\"
XCOPY "U:\sourcedir\misc\90s\extended\Kelly Rowland - Work (Freemasons Arabic Mix).mp4" "c:\new\extended\"
XCOPY "U:\sourcedir\one\dummyfile1.mp4" "c:\new\one\"
XCOPY "U:\sourcedir\t w o\dum myfile2.mp4" "c:\new\t w o\"
XCOPY "U:\sourcedir\t w o\dum ile2.mp4" "c:\new\t w o\"
With enabledelayedexpansion in for loop, you should use !newDir! instead of %newDir%, and also !currDir:~13! instead of %currDir:~13% to make delayed expansion happen.
[update] There're also small errors. You should be careful about the spaces and quotes when you set to variables. They are actual part of the string to be set. And you have mkdir the same directory several times, and also it's better to user copy or xcopy instead of 'cp' which should be from "Cygwin" or "MinGW32" or something. xcopy will automatically create folders for you if not exist.
To make your codes work, please see below. And just a suggestion that you'd better learn more basic knowledge about bat before starting programming.
#echo off & setlocal enabledelayedexpansion
FOR /R %%X in ("*.mp4") DO (
set currDir=%%~pX
set newDir=!currDir:~13!
REM mkdir "C:\new\!newDir!"
REM convert mp4 here
xcopy "%%X" "C:\new\!newDir!"
)