Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: Issue regarding variable initialization in dos script  (Read 3494 times)

0 Members and 1 Guest are viewing this topic.

asmfloyd

    Topic Starter


    Newbie

    • Experience: Experienced
    • OS: Windows 7
    Issue regarding variable initialization in dos script
    « on: May 24, 2019, 02:30:41 PM »
    Hello Gurus,
      I have script which will pull the filenames of a folder as "xyz01.csv". Then extracts the 2 digit before dot and creates folder of that name (Ex:01) .Then move the file into that new folder. Below is the one I wrote. Somehow the variable is not working correctly which gives the folder name incorrectly. I added the SetLocal function in the begin but does not help me.
     Any help is highly appreciated.

    Thanks,



     @echo off
    SetLocal EnableDelayedExpansion
    cls

    set  SourceDir=C:\TEMp\WORK_TEST\INPUT\
    set TargetDir= "C:\TEMp\WORK_TEST\OUTPUT\"

    REM:::  ------------CODE FOR CSV

    for %%i in (%SourceDir%*.csv) do (

        set var=%%i
        set substr6=%var:~-6,-4%
          echo !var[%%i]!
          echo !substr6!
        echo !substr6!---Extracts 6digits from end then remove the last 4


       IF EXIST %TargetDir%%substr6% (

          echo folder exists
          move %%i  %TargetDir%%substr6%

       ) ELSE (

          echo folder do not
          mkdir  %TargetDir%%substr6%
          move %%i  %TargetDir%%substr6%

       )


    )

    Sidewinder



      Guru

      Thanked: 139
    • Experience: Familiar
    • OS: Windows 10
    Re: Issue regarding variable initialization in dos script
    « Reply #1 on: May 27, 2019, 09:14:37 AM »
    Variables created within a for loop must be wrapped with ! signs not % signs. Also used the base name portion of the file name to keep it simple: set var=%%~ni

    Code: [Select]
    @echo off
    SetLocal EnableDelayedExpansion
    cls

    set  SourceDir=C:\TEMp\WORK_TEST\INPUT\
    set TargetDir= "C:\TEMp\WORK_TEST\OUTPUT\"

    REM:::  ------------CODE FOR CSV

    for %%i in (%SourceDir%*.csv) do (

        set var=%%~ni
        echo !var!
        set substr6=!var:~-2!
        echo !var[%%i]!
        echo !substr6!
        echo !substr6!---Extracts 6digits from end then remove the last 4


       IF EXIST %TargetDir%!substr6! (

          echo folder exists
          move %%i  %TargetDir%!substr6!

       ) ELSE (

          echo folder do not
          mkdir  %TargetDir%!substr6!
          move %%i  %TargetDir%!substr6!

       )


    )

    Good Luck.  8)
    The true sign of intelligence is not knowledge but imagination.

    -- Albert Einstein