views:

53

answers:

2

How to write a Batch program that can move files with .txt from a folder (including files in sub-folder) in to a different folder and rename it in the form folderName_subfolderName_Filename.extension

+1  A: 

This following snippet should do the trick. Modify it to your needs.

@ECHO OFF
REM Put the source and destination folde names here.
REM You can use %1 and %2 instead if you want to pass
REM folders as command line parameters

SET SOURCE_FOLDER=C:\SRC
SET TARGET_FOLDER=C:\DST

REM This is needed for variable modification inside the FOR loop
SETLOCAL ENABLEDELAYEDEXPANSION

REM The FOR loop lists all files recursively beginning in
REM %SOURCE_FOLDER% matching the *.txt pattern.
REM Filenames can be accessed in th loop via the %%F variable
FOR /R %SOURCE_FOLDER% %%F IN (*.txt) DO (

   REM Put the path and filename into the FILE_NAME variable
   SET FILE_NAME=%%~pnxF

   REM Transform the path to new filename 
   REM (replace '\' with '_' and strip the first '\')
   SET FILE_NAME=!FILE_NAME:\=_!
   SET FILE_NAME=!FILE_NAME:~1!

   REM This is the actual MOVE command creating the 
   REM targest filename from the variables.
   MOVE "%%F" "%TARGET_FOLDER%\!FILE_NAME!"
)
Frank Bollack
Your are Genius thanks :) , by the way i have some doubts in their working can you put a comment beside the code so that I can clearly understand
subanki
A: 

Hello,

adopted solution:

usage: moveit TargetFolder DestinationFolder NameOfTargetFolder

Sample: moveit C:\MyFolder C:\MySecondFolder MyFolder

moveit.bat:

Set target=%~1
Set destination=%~2
Set prefix=%~3

for /f "tokens=*" %%f in ('dir /b %target%\*.txt') do move "%target%\%%f" "%destination%\%prefix%_%%f"

for /f "tokens=*" %%s in ('dir /b/ad %target%\*') do call moveit.bat "%target%\%%s" "%destination%" %prefix%_%%s
RoXX
Thanks a lot :)
subanki
I wanna name it according to folder hierarchy like FolderName_subFolderName1_SubFolderName2_subFolderNAme3....._SubFolderNameN.txt
subanki
So a File Folder\Subfolder\Subfolder2\Filename.txt would be Folder_Subfolder_Subfolder2_Filename.txt?
RoXX
yes thats right also as a request please see this guy need , its something similar http://superuser.com/questions/187967/batch-script-to-batch-rename-files-or-use-a-tool
subanki
ok so i adopted the solution to do this job!
RoXX