Extract only the last word from a string

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
lyp
Posts: 1
Joined: 17 Oct 2014 15:44

Extract only the last word from a string

#1 Post by lyp » 17 Oct 2014 15:48

Hi all!

I can't find answer to the following question: How can I extract only the last word from a string?

Thanks

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Extract only the last word from a string

#2 Post by foxidrive » 17 Oct 2014 17:49

Here is one way:

If you want to do something else then give us full details of the task.

Code: Select all

@echo off
set "string=A cat and dog had a quarrel"
echo "%string%"|repl ".* (.*)." "$1"
pause



This uses a helper batch file called `repl.bat` (by dbenham) - download from: https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat

Place `repl.bat` in the same folder as the batch file or in a folder that is on the path.

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: Extract only the last word from a string

#3 Post by Squashman » 17 Oct 2014 19:22

Code: Select all

@echo off
set string=Give me the last word in this sentence
FOR %%A IN (%string%) DO SET last=%%A
echo %last%
pause

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Extract only the last word from a string

#4 Post by foxidrive » 17 Oct 2014 19:52

Put an ampersand in there and BANG! ;)

Yury
Posts: 115
Joined: 28 Dec 2013 07:54

Re: Extract only the last word from a string

#5 Post by Yury » 18 Oct 2014 04:00

foxidrive wrote:Put an ampersand in there and BANG! ;)




Without the Bing Bang:


Code: Select all

@echo off
setlocal enabledelayedexpansion

set "string=|| <> :&"

for /f "delims=" %%i in ('cmd /u /c set /p"=%string%"^<nul^| more^| findstr /n "^"') do (
 set symbol=%%i
 if not "!symbol:*:=!"==" " (set last=!last!!symbol:*:=!) else (set last=)
 )
for /f "eol=" %%i in ("%last%") do echo %%i

endlocal
pause>nul
exit /b



.

ghostmachine4
Posts: 319
Joined: 12 May 2006 01:13

Re: Extract only the last word from a string

#6 Post by ghostmachine4 » 31 Oct 2014 21:52

vbscript, using arrays

Code: Select all

myString = "one two three four five"
myArray = Split(myString)
WScript.Echo myArray( UBound(myArray) )

Post Reply