nzsquall
nzsquall

Reputation: 405

CMD command to find a file and do something with this file

I want to use a batch file to find a file in my system and play with it.

I can use

dir filename /s /p 

to find the location.

For example, if I ran the following

C:\Users\test>dir somejar.jar /s /p
 Volume in drive C is OS
 Volume Serial Number is 981C-D5F0

 Directory of C:\Users\test\.gradle\caches\artifacts-24\filestore\org.something\jar\1bd8c9fd8aee6dcac27f6d727a15eb7c65532e0

07/04/14  07:35 p.m.         2,530,874 somejar.jar
               1 File(s)      2,530,874 bytes

     Total Files Listed:
               1 File(s)      2,530,874 bytes
               0 Dir(s)  194,490,933,248 bytes free

C:\Users\test>

How do I make a batch file so once I open it, it will find this file and change its directory to where the file is located and play with this file?

Thank you.

Upvotes: 0

Views: 154

Answers (1)

Thomas Weller
Thomas Weller

Reputation: 59670

You can try

for /F "delims=" %s in ('dir /s /b filename') do cd "%s\.."

on the command line or replace %s by %%s to use in a batch file. How it works:

  1. It uses dir /s as proposed by you, but without paging. Instead I use the simple output format (bare) /b to just get the file name.
  2. Because we can't simply pipe (|) this into cd, we need the strange for command. Make sure that for does not start splitting at backslashes (/F "delims=").
  3. Because we get the file name but want the directory instead, use \.. to go up one level (from file to directory).

Upvotes: 1

Related Questions