Search code examples
for-loopsubstringbatch-file

Equivalent of cut command in DOS not working within for loop?


I am trying to use the cut equivalent for DOS but it is not working in my for loop.

Content of weekly_date.txt

18092012                                                                        
19092012                                                                        
20092012                                                                        
21092012                                                                        
22092012                                                                        
23092012                                                                        
24092012                                                                        

I am running a batch script & facing a variable value substitution problem in below part:

for /f %%I in (weekly_date.txt) do ( 

echo %%I
set yy=%%I:~4,4%
set mm=%%I:~2,2%
set dd=%%I:~0,2%

echo %yy%

SET bp=/xx/yy/%mm%/%dd%
SET br=/aa/bb/%mm%/%dd%
SET TP=F:\xx\%yy%\%mm%\%dd%\yy

echo %bp%
echo %br%
echo %TP% )

done

Then in

SET bp=/xx/yy/%/%mm%/%dd%
SET br=/aa/bb/%/%mm%/%dd%
SET TP=F:\xx\%yy%\%mm%\%dd%\ff 

It's getting substituted in below manner when running batch script

SET bp=/xx/yy/%i:~2,2/%i:~0,2  
SET br=/aa/bb/%i:~2,2/%i:~0,2  
SET TP=F:\xx\%i:~4,4\%i:~2,2\%i:~0,2\ff   

Actually the output must be

/xx/yy/09/18
/aa/bb/09/18
F:\xx\2012\09\18\ff


/xx/yy/09/19
/aa/bb/09/19
F:\xx\2012\09\19\ff

....
...

/xx/yy/09/24
/aa/bb/09/24
F:\xx\2012\09\24\ff

Can any one point out where I am going wrong?


Solution

  • For your code I would make two main changes: 1)set the input of the for loop to another variable (called var) for manipulation 2)Enable delayed expansion, which allows the variable to be manipulated with each for loop iteration. Let me know if any additional changes need to be made to my code =]

    My code is as follows:

    @echo off
    setLocal EnableDelayedExpansion
    
    for /f %%I in (weekly_date.txt) do ( 
    set var=%%I
    set yy=!var:~4,4!
    set mm=!var:~2,2!
    set dd=!var:~0,2!
    
    set bp=/xx/yy/!mm!/!dd!
    set br=/aa/bb/!mm!/!dd!
    set TP=F:\xx\!yy!\!mm!\!dd!\ff
    
    echo !bp! !br! !TP!
    )
    
    endlocal
    

    Using the same weekly_dates.txt input you provided, the output of this code is:

    /xx/yy/09/18 /aa/bb/09/18 F:\xx\2012\09\18\ff 
    /xx/yy/09/19 /aa/bb/09/19 F:\xx\2012\09\19\ff 
    /xx/yy/09/20 /aa/bb/09/20 F:\xx\2012\09\20\ff 
    /xx/yy/09/21 /aa/bb/09/21 F:\xx\2012\09\21\ff 
    /xx/yy/09/22 /aa/bb/09/22 F:\xx\2012\09\22\ff 
    /xx/yy/09/23 /aa/bb/09/23 F:\xx\2012\09\23\ff 
    /xx/yy/09/24 /aa/bb/09/24 F:\xx\2012\09\24\ff