Reputation: 1661
I have a c:\test
directory which has a text file var_list.txt
with these 3 lines:
abc
xyz
def
I have a C:\test\source
directory which has a text file source_file.txt
.
I have a C:\test\target
directory which is empty.
I want to write a windows batch file which do these tasks:
var_list.txt
line by line in a variable source_file.txt
from C:\test\source
directory to
C:\test\target
directory with the file name also having the variable line appended to it in its nameSo when I run this windows batch file, I want it to create these 3 files:
So I create a windows batch file create_target_files.bat
in c:\test
directory with these contents:
@echo off
for /f "tokens=*" %%a in (var_list.txt) do (
echo line=%%a
copy /Y /V C:\test\source\source_file.txt C:\test\target\target_file_%a%.txt
)
pause
When I run it I get this output:
line=abc
1 file(s) copied.
line=xyz
1 file(s) copied.
line=def
1 file(s) copied.
Press any key to continue . . .
But in C:\test\target
directory only 1 file target_file_.txt
is created. Why 3 files are not created with variable names?
Upvotes: 1
Views: 592
Reputation: 18827
You can do something like that :
@echo off
setlocal enabledelayedexpansion
for /f "tokens=*" %%a in ('Type "C:\test\var_list.txt"') do (
Set "line=%%a"
echo !line!
Copy /y /v "C:\test\source\source_file.txt" "C:\test\target\target_file_!line!.txt"
)
pause & exit
For more information how and when to use Enabledelayedexpansion
Upvotes: 0
Reputation: 403
There is a small mistake in your code.
copy /Y /V C:\test\source\source_file.txt C:\test\target\target_file_%a%.txt
In this line of code, you are using %a%
instead of %%a
.
Since you did not assign the variable, %a%
would give you a blank string.
Therefore, all copied files are named target_file_.txt and they are overwritten by the last file.
Upvotes: 1