how to manipulate the file names

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
marimo
Posts: 4
Joined: 05 Aug 2009 12:31

how to manipulate the file names

#1 Post by marimo » 05 Aug 2009 12:40

Hi,

I have some files in the directory "A".

a.txt
b.txt
c.txt
d.txt
z.txt
master_yyyymmdd.txt


I want to move the files (a,b,c,d,z) to the directory "History" based on master_yyyymmdd file.

for example,

after the move, the files will be a_20090804.txt , b_20090804.txt, c_20090804.txt,...etc

Is that possible?

avery_larry
Expert
Posts: 391
Joined: 19 Mar 2009 08:47
Location: Iowa

#2 Post by avery_larry » 05 Aug 2009 13:56

Code: Select all

@echo off
setlocal enabledelayedexpansion
set "folder=c:\path\to\your\files"

::First extract the date portion of the master_yyyymmdd.txt file
::It MUST be in that format.
for /f "tokens=2 delims=_." %%a in ('dir "%folder%\master_*"') do set "date=%%~a"

::Next we get the filenames in the directory, make sure it's not the master_yyyymmdd.txt file,
::and then move them into the history folder with the new name.
for /f %%b in ('dir /b /a-d "%folder%"') do (
   set "filename=%%~b"
   if not "!filename:~0,6!"=="master" move "%folder%\%%~b" "%folder%\history\%%~nb_%date%%%~xb"
)


marimo
Posts: 4
Joined: 05 Aug 2009 12:31

#3 Post by marimo » 05 Aug 2009 14:17

just a little change..
My user came back to me and said they want to rename the master file to
"Master_mm_yyyy.xls"

I changed the syntax a little and works now.

for /f "tokens=2,3 delims=_." %%a in ('dir "%folder%\master_*"') do set "date=%%~a_%%~b"


Except master_* is case-sensitive. so It moved Master_* file to history directory. not sure how to ignore the case sensitive though.

avery_larry
Expert
Posts: 391
Joined: 19 Mar 2009 08:47
Location: Iowa

#4 Post by avery_larry » 06 Aug 2009 10:18

Oops -- need /i on the if statement like this:

Code: Select all

if /i not "!filename:~0,6!"=="master" move "%folder%\%%~b" "%folder%\history\%%~nb_%date%%%~xb" 

marimo
Posts: 4
Joined: 05 Aug 2009 12:31

#5 Post by marimo » 06 Aug 2009 12:48

excellent!

rfpd
Posts: 78
Joined: 06 Jul 2009 16:19
Location: Lisbon, Portugal
Contact:

w

#6 Post by rfpd » 07 Aug 2009 07:56

why you want a super code why don't you use a simple rename??????

avery_larry
Expert
Posts: 391
Joined: 19 Mar 2009 08:47
Location: Iowa

Re: w

#7 Post by avery_larry » 07 Aug 2009 09:14

rfpd wrote:why you want a super code why don't you use a simple rename??????
Because there might be thousands of files, and also presumably the master_yyyymmdd.txt file will change often. One piece of code will take care of both things, otherwise you have to manually enter multiple move commands.

Post Reply