I have 3 folders such as the below structure wise. . .
- /location1
- /subdirLocation1
- foo-bar1.txt, foo-bar2.txt, foo-bar3.txt
- /location2
The subdirLocation1
folder is a sub-directory of location1
. The location1
folder also contains the files foo-bar1.txt
, foo-bar2.txt
, foo-bar3.txt
. However, the location2
folder is empty.
Folder Structure Recap
- location1 > subdirLocation1, foo-bar1.txt, foo-bar2.txt, foo-bar3.txt
- subdirLocation1 > foo-bar-subdir.txt
- location2 > (Empty)
I want to move all .txt files from location1
and its subdirectories to location2
, and also rename these .txt files by replacing every "-" with "_" so every hyphen character in the file names becomes an underscore character instead.
I need to achieve this task using a Windows batch script?
Here's what I came up with originally before I added additional logic I came up with using FOR loops below that as well near the bottom of my answer.
This however only moves .txt files from location1
directory and not from its subdirectory. Also renaming only works for foo-bar1.txt
, foo-bar2.txt
, foo-bar3.txt
. It would not work for foo-bar-subdir.txt
.
MOVE "C:\Users\abcde\Desktop\Practice_Folder\batch rename\location1\*.txt" "C:\Users\abcde\Desktop\Practice_Folder\batch rename\location2"
RENAME "C:\Users\abcde\Desktop\Practice_Folder\batch rename\location2\*-*" ???_????.txt
Below is what I have that's working a little better than the above but the hyphen characters are not being replaced with the underscores in the file names
CD "C:\Users\abcde\Desktop\Practice_Folder\batch_rename\location1\"
for /R %%f in (*-*.txt) do call :copyFile %%f
goto: eof
:copyFile
xcopy %1 "C:\Users\abcde\Desktop\Practice_Folder\batch_rename\location2"
set file=%~nx1
rename file %str:-=_%
Answer
I want to move all .txt files from location1 and its subdirectories to location2, and also rename these .txt files by replacing every "-"
with "_".
Since you're commented back with a ton of Batch work you've put into this, I wanted to share a script with you that should help for how you explain you need this to work.
Please be sure to test and confirm all works as expected on your side with test data before you run against anything critical or production related.
Script Example
You shouldn't need to use the comment out logic but it's there in case you need it
@ECHO ON
SET Loc1Dir=C:\Users\abcde\Desktop\Practice_Folder\batch_rename\location1
SET Loc2Dir=C:\Users\abcde\Desktop\Practice_Folder\batch_rename\location2
CD /D "%Loc1Dir%"
FOR /R %%F IN ("*-*.txt") DO CALL :copyFile %%~F %%~NXF
GOTO: EOF
:copyFile
SET copyfname=%~1
SET fname=%~2
SET fname=%fname:-=_%
ECHO F | XCOPY /Y /F "%copyfname%" "%Loc2Dir%\%fname%"
:::XCOPY /Y /F "%copyfname%" "%Loc2Dir%\"
:::REN "%copyfname%" "%fname%"
GOTO :EOF
No comments:
Post a Comment