Batch file get last part of path
For example, given the following path:. I need to parse that value out as its name will be part of another folder I am going to create further down in the batch file. Many thanks if anyone can help. I may be barking up the wrong tree completely so any other approaches would be greatly received also.
After struggling with some of these suggestions, I found an successfully used the following 1 liner in windows I found this old thread when I was looking to find the last segment of the current directory. The previous writers answers lead me to the following:. The trick is that we take the desired path, back up one level to create a folder mask for substitution and then replace the folder mask with nothing. To test it, simple copy and paste into a command script.
How do I store the last part of directory in a variable? Improve this question. Ben Pilbrow 12k 5 5 gold badges 34 34 silver badges 57 57 bronze badges. You might have more joy with this over on SuperUser superuser. Add a comment. Active Oldest Votes. Improve this answer.
It is possible to keep this a one liner by omitting the echo and directly do the set. This doesn't work if the path ends with a slash. Dennis Williamson Dennis Williamson 59k 14 14 gold badges silver badges bronze badges. MohammadAL-Rawabdeh: You said "from a command line".
If you're doing it in a batch file, you'll need to use double percent signs. But there is a much simpler solution that works always:. The inner call to GetDirectoryName will return the full path, while the outer call to GetFileName will return the last path component - which will be the folder name.
This approach works whether or not the path actually exists. This approach, does however, rely on the path initially ending in a filename. Active Oldest Votes. It looks like it is becuase you didn't have a trailing slash at the end.
If you append one, the above will work. To make it safe you can check if there is a trailing slash and if so delete the last char and if not let the string as it is : — geisterfurz When there are spaces in the path above method doesn't work. Show 6 more comments. Endoro Endoro Dirk Dirk 1 1 silver badge 4 4 bronze badges. To put it in an easy subroutine that properly handles spaces: Echo Off Rem Get name of folder containing this script. Bilbo Bilbo 1 1 silver badge 9 9 bronze badges.
REM It also allows us to limit delayed variable expansion to where it's needed. REM If it already had a trailing slash, that's okay: extras are ignored. REM Use loop variable expansion to get the "path" part of the path.
0コメント