Saturday, March 25, 2017

How can I make windows command prompt return a substring from a command ouput



My path is pointed towards a cloud folder (located at various places on my various devices) wherein I have stored a batch file that is supposed to locate itself on the machine, and then make that directory the new working directory of that session.



Locating the file



@echo off No clutter



cls clean slate




Echo Searching Because sometimes it takes a while



dir /b /s myScripts.bat And this outputs the full directory, including the file name.



So my first problem is getting rid of the file name. This is what I've tried:



set stringOne=dir /b /s myScripts.bat



%stringOne:~0, 60%




I found a script for counting the length of a string which I'll use to automatically deduce those values later if it turns out I actually need them.



Problem is I've found that if I lower that number to 10, the dir command is shortened like so:



dir c:\users\myUsername\cloudDrive\scripts, or whatever the case may be,
and instead cmd inputs dir c:\users\m and searches ALL of that recursively.



Again, what I'd like to do is have it show me a modified version of the directory it searched, NOT modify the directory search command. I'll later use the final string produced to set my working directory to, but I'm trying to take this one step at a time so I understand what is happening.




EDIT:
The ultimate goal of the SCRIPT is different from my purpose for writing it. When all is said and done I should be able to type myScripts.bat into cmd, on any computer which I have appended to it's PATH my cloud folder, and it will procure the directory of that cloud folder via means of the dir command, and then change it's working directory to that of the batch file.


Answer



To answer this part:




And this outputs the full directory, including the file name. So my
first problem is getting rid of the file name.





In a batch file you can do



@echo off

:: locate 'myScripts.bat' and save its directory to 'myDir'
:: in case of multiple matches 'myDir' will be set to the last one
set "myDir="
for /f "delims=" %%x in ('dir /b /s myScripts.bat') do set "myDir=%%~dpx"
if not defined myDir echo not found ?? & exit /b 1


:: ready to use
echo myDir = "%myDir%"


To get a better hang of batch files, I recommend that you read the builtin help, starting with set /?, if /?, for /?, call /?.



[ EDIT ] Added "delims=" to handle paths with spaces correctly.


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...