Reputation: 13
I'm trying to make a batch file to copy files from a text list to a folder. The code was copied in this forum but it doesn't work.
The text list is in the desktop.
list.txt
and contains, for example,
C:\Users...\Desktop\Test\item1.ipt
C:\Users...\Desktop\Test\item2.ipt
C:\Users...\Desktop\Test\item3.ipt
C:\Users...\Desktop\Test\item4.ipt
C:\Users...\Desktop\Test\item5.ipt
C:\Users...\Desktop\Test\item6.ipt
and my batch file is also in the desktop.
@echo off
FOR /F "delims=" %%a IN (C:\Users\...\Desktop\list.txt) DO COPY "%%~a" "C:\Users\...\Desktop\Temp\%%~nxa"
Both files (batch and txt) are in the desktop, so can I delete the path of the text file?
@echo off
FOR /F "delims=" %%a IN (list.txt) DO COPY "%%~a" "C:\Users\...\Desktop\Temp\%%~nxa"
Thanks for your help.
EDIT: The ideia is to get the file location in the text file, so directories in the text file are variables.
Upvotes: 0
Views: 5186
Reputation: 30238
@echo off
pushd "%userprofile%\Desktop"
FOR /F "delims=" %%a IN (list.txt) DO COPY "%%~a" ".\Temp\%%~nxa"
popd
In the above code snippet:
pushd
command: Change the current directory/folder and store the previous folder/path for use by the POPD
command.%userprofile%
is a standard (built-in) Environment Variable".\Temp\%%~nxa"
is a directory component in a path representing the current directory. Hence, ".\Temp\%%~nxa"
has the same effect as "Temp\%%~nxa"
.POPD
command: Change directory back to the path/folder most recently stored by the PUSHD
command.Edit. Above ´for /F´ loop does do nothing silently if the list.txt
is empty, or if it contains only empty lines and standard delimiters, or if it start with some control characters, e.g. NULL
character, or if it is saved using UTF-16
encoding.:
==> type null_and_data.txt
1st line
2nd
3rd
==> FOR /F "delims=" %a IN (null_and_data.txt) DO @echo "%~a"
==> powershell -c "(type null_and_data.txt -Encoding byte -TotalCount 16) -Join ','"
0,49,115,116,32,108,105,110,101,32,13,10,50,110,100,13
==>
Some of above scenarios (in particular, the latter one) could be solved by using type
command as follows:
@echo off
pushd "%userprofile%\Desktop"
FOR /F "delims=" %%a IN ('type list.txt') DO COPY "%%~a" ".\Temp\%%~nxa"
popd
Example:
==> FOR /F "delims=" %a IN (fileUTF16LEBOM.txt) DO @echo "%~a"
==> type fileUTF16LEBOM.txt
x
y
==> FOR /F "delims=" %a IN ('type fileUTF16LEBOM.txt') DO @echo "%~a"
"x"
"y"
==>
Upvotes: 2