Page 1 of 1

Extract only the last word from a string

Posted: 17 Oct 2014 15:48
by lyp
Hi all!

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

Thanks

Re: Extract only the last word from a string

Posted: 17 Oct 2014 17:49
by foxidrive
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.

Re: Extract only the last word from a string

Posted: 17 Oct 2014 19:22
by Squashman

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

Re: Extract only the last word from a string

Posted: 17 Oct 2014 19:52
by foxidrive
Put an ampersand in there and BANG! ;)

Re: Extract only the last word from a string

Posted: 18 Oct 2014 04:00
by Yury
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



.

Re: Extract only the last word from a string

Posted: 31 Oct 2014 21:52
by ghostmachine4
vbscript, using arrays

Code: Select all

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