Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting A variable with the first word from another variable [closed]

I need to pull the first word from a variable in my batch script to another variable.

ex

if %hello% had "apples are awesome" in it and was pulled and put into %hi%

%hi% would say "apples"

thanks in Advance

like image 792
GeriatricJacob Avatar asked Apr 11 '26 19:04

GeriatricJacob


1 Answers

This can be done using a for loop:

for /f %%h in ("%hello%") do [command that uses %%h]

The behaviour of "for" in this circumstance is to split its input up into lines (there is only one, assuming there are no newline characters in your input variable), then split each line into tokens on spaces (you can change the delimiter using the "delim=[chars]" option) and pass the first token of each line to the specified command (you can use "tokens=n,n,..." to get at tokens other than the first on the line).

Note that AIUI you can only use a single letter variable name for the variable to receive the word, so you can't use %%hi as you requested.

(This is all untested, as I'm not at a machine running Windows at the moment, but ought to work if I'm reading the documentation correctly.)

like image 143
Jules Avatar answered Apr 14 '26 13:04

Jules