开发者

Remove the parent directory name from the echo %cd% command

We know that echo %cd% command print working directory, Assume that it is "C:\test\bin\run" I want to know how to remove "run" from the string. second time "run" directory can be "stop" directory. therefore we can't use string replace command. what is I think to do is remove the string after last "\". Anyone know how to d开发者_Go百科o this in windows commandline(cmd)


If it's okay to change dirs during the process how about:

set x=%cd%
cd ..
set parent=%cd%
cd %x%


in commandline this works:

C:\dir\folder>FOR /F "tokens=3 delims=\" %A IN ('echo %CD%') DO SET FOLDER=%A

Now the environment variable FOLDER contains the value "folder"

I used tokens=3 because folder is the third token after the \-delimiters

If you used tokens=2 the environment variable FOLDER contained the value "dir"

If you used tokens=1 the environment variable FOLDER contained the value "c:"

it should also work in Batch Files if you replace %A by %%A like follows:

FOR /F "tokens=3 delims=\" %%A IN ('echo %CD%') DO SET FOLDER=%%A

Based on this you can build a loop that repeats until FOLDER is empty string. In the loop you would need to assign FOLDER to LASTFOLDER at each step. After the loop is done, LASTFOLDER contains the Folder of your current Directory. You also could put the code into a seperate script "GetBaseFolder.BAT" and use "call GetBaseFolder %CD%" in the main Batch.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜