Tuesday, May 31, 2011

How would I search for a file by using command prompt, and then change to that directory automatically?

Say I have a text file named ';hello.txt';. I'm not sure where that file is on my computer however. So I make a batch file that does ';dir /s haha.txt'; and it lists where the file is found. What would I need to add to that batch file to automatically switch to that directory? I don't want to do any of this manually...I want it totally automated by the batch file. This is just a simple example mind you, I just want to be able to have the functionality I'm asking for. And yes, I'm sure there are more simple ways to do this, etc. But I want to know if there is a way to do exactly what I'm asking. Thanks.How would I search for a file by using command prompt, and then change to that directory automatically?
Assuming you have a ';modern'; version of Windows (ie: something with ';cmd.exe'; rather than ';command.com';) you can do something like this:



for /f %%f in ('dir /s/b hello.txt') do set pathname=%%f

set dirname=%pathname:~0,-9%

cd /d %dirname%



Note that if it finds more than one ';hello.txt';, this will go to the directory of the last one found.



The ';for'; loop will execute the ';dir'; command, and set the variable ';pathname'; to hold the full path of the hello.txt file.



The ';set'; line sets ';dirname'; to everything execpt the last 9 characters of ';pathname';. That is, it removes ';hello.txt'; from the end, leaving just the path to the directory. If you change the filename, you need to change the number appropriately.



Finally, ';cd'; sets the current directory.





- kb -How would I search for a file by using command prompt, and then change to that directory automatically?
Install the cygwin tools and you will get windows versions of the time-tested unix/linux tools. Then you can even use bash shell scripts instead of ms-DOG batch files.
what do you mean switch directory? like..move the file to a different director? i fail to understand this question :P

No comments:

Post a Comment