Search code examples
directoryfinddos

DOS extract directory from find command


I am writing a dos script and I want to get the path of a file that is known so that the path can be used within the script to change to that directory to use the file specified and ouput log files to the same directory.

The script adds some directories to the path and changes to the required directory to execute a command using input files in the same directory. The command generates a number of files that are saved to the same directory.

Here is what i have so far

@ECHO OFF

:: Check argument count
set argC=0
for %%x in (%*) do Set /A argC+=1

IF %argC% LSS 3 (echo WARNING must include the parent Directory, the filename and the timestep for the simulation)

:: Assign meaningfull names to the input arguments
set parentDirectory=%1
set filename=%2
set scenarioTimestep=%3

:: Check validaty of the input arguments
:: TODO: implement check for directory, filename exists, and possibly limits to the timestep 
IF "%parentDirectory%"=="" (
    set parentDirectory=P:Parent\Directory
) 
IF "%filename%"=="" (
    set filename=ship2.xmf
) 
IF "%scenarioTimestep%"=="" (
    set scenarioTimestep=0.1
) 

echo parent Directory: %parentDirectory%
echo filename: %filename%
echo timestep: %scenarioTimestep%

set MSTNFYURI=file:mst.log
set MSTNFYLEVEL=debug
set MSTNFYFLUSH=1

set XSFNFYURI=file:xsf.log
set XSFNFYLEVEL=debug
set XSFNFYFLUSH=1

set parentNFYURI=file:parent.log
set parentNFYLEVEL=debug
set parentNFYFLUSH=1

:: Add the parent directories to the path
set PATH=%parentDirectory%\bin\;%parentDirectory%\bin\ext\;%parentDirectory%\bin\gtkmm\;%parentDirectory%\bin\osg\;%PATH%

:: Change to the target directoy
set tagetDirectory=%parentDirectory%\examples\testing_inputs
cd %tagetDirectory%

echo command will be: ft -c %filename% -T %scenarioTimestep%
::ft -c %filename% -T %scenarioTimestep%

@ECHO ON

What i want to be able to do is instead of using the hard coded directory path examples\testing_inputs for targetDirectoy, i want to be able to search for the filename supplied and change directory to that path.

I know i can get the information displayed using "dir filename.ext /s"

DOS ouptut

Volume in drive C is OS
Volume Serial Number is XXXX-XXXX

Directory of C:\Users\Me\parent\examples\testing_input

15/11/2012   02:51 PM    <size> filename
...
...

How do i extract the directory form this info to be used within the script? Also if there is more than one file of the same name, how can i select the path based on the timestamp of the file?


Solution

  • for /f %%F in ('dir /B /S /A:-D  filename.ext ') do set file_path=%%F
    pushd  %file_path%\..
    dir_path=%CD%
    popd
    echo %file_path%
    echo %dir_path%
    

    is this what you looking for?

    EDIT: Check dbenham's comment.