chaliasos
chaliasos

Reputation: 9783

How to get the last word of a string?

I have a batch file which takes as an argument a file path

set filePath = %1

Now, lets say the file path is: C:\Temp\Folder, I want to set the Folder in a new variable. How can I do that?

I search on the web and all solutions are something like this:

for %%A in (%filePath%) do set last=%%A

but this works only for string with spaces.

Upvotes: 3

Views: 7694

Answers (3)

VladimirT
VladimirT

Reputation: 1

you can try

for /F "tokens=4*" %%G IN (Data.txt) DO (
set value1=%%G
echo %value1%
)

4* is the number of the word that you want to take

Upvotes: 0

Andriy M
Andriy M

Reputation: 77657

You can extract Folder from C:\Temp\Folder by applying the ~n modifier to %1:

SET "last=%~n1"

If the last item may contain ., use ~nx instead:

SET "last=%~nx1"

The ~n modifier applies to a positional parameter or a loop variable and extracts the last name from the path specified by that parameter or variable. The ~x modifier extracts the extension of the last name (the part starting from the last .). Accordingly, ~nx extracts both the (last) name and the extension.

Upvotes: 3

You can replace the slashes with a space, and then parse it out:

set filePath=%1
set filePath=%filePath:\= %
for %%A in (%filePath%) do set last=%%A

Upvotes: 3

Related Questions