Page 1 of 1

Split directory name & filename from a string

Posted: 29 Jan 2009 12:56
by santoshsri
Wondering if there is any way to split directory name & filename from a string that contains a complete path of file including filename.

Posted: 03 Feb 2009 22:08
by DosItHelp
santoshsri,

Use a FOR loop like this:

Code: Select all

@echo off
Set filename=C:\Documents and Settings\All Users\Desktop\Dostips.cmd
For %%A in ("%filename%") do (
    Set Folder=%%~dpA
    Set Name=%%~nxA
)
echo.Folder is: %Folder%
echo.Name is: %Name%

Output will be:
Folder is: C:\Documents and Settings\All Users\Desktop\
Name is: Dostips.cmd

See also the help for the FOR command:
http://www.dostips.com/DosCommandIndex.htm#FOR
DosItHelp? :wink:

Posted: 04 Feb 2009 10:37
by RElliott63
Along those same lines... what is the easiest way to deal with looping through a directory set that includes spaces (ie "Documents and Settings")?

I have a situation where I need to find specific files (wildcard search) on a drive to do a secure delete on these specific files. I know I can do this with a "Dir /s/b", but if the files are included with a directory that has spaces, there are identification situations that are hosed due to the spaces.

Currently, I am looking at:

Code: Select all

   
   Set LookUpSet=Dir /b/s File1* File2*
   For /F %%F In ('%LookUpSet%') DO (

       Echo;
       Echo Path:   %%~fF
       Echo File:   %%~nxF
       Echo;

       Pause

   )


When I get to a File1* entry that happens to be in "Documents and Settings" the reply is:

Code: Select all

Path:   C:\Documents
File:   Documents


Thanks for your help!

-Rick

Posted: 04 Feb 2009 22:24
by DosItHelp
RElliott63,
FOR /F uses spaces as default delimiter. Empty the delimiter set using FOR /F "delim=", i.e.:

Code: Select all

Set LookUpSet=Dir /b/s File1* File2*
For /F "delim=" %%F In ('%LookUpSet%') DO (
       Echo;
       Echo Path:   %%~fF
       Echo File:   %%~nxF
       Echo;
       Pause
)

Let us know if it works for you.

Posted: 05 Feb 2009 09:11
by RElliott63
Thanks for the advice. After playing around with it yesterday afternoon, I ended up with the following:

Code: Select all

 
 Set LookUpSet=Dir /b/s File1* File2 File3*
   
 For /F "Delims=" %%F In ('%LookUpSet%') DO (

     Set "f=%%~nxF"
     Set "p=%%~pF"

     CD /D "!p!"
       
     Call :LogMsg "Flagged for Removal"
     Call :RemoveFile
     Call :LogMsg "Removed"

 )


Code: Select all

 
:: File Removal
 :RemoveFile

 Echo --Changing Directory to:  !p!
 CD /D !p!
 
    Echo --Removing File:  !f!

    Call :LogMsg "Removing !f! from Folder..."
    SDelete -p 5 !f!

 Goto:EOF


Thanks for the help!

-R