0

Trying to create a batch file that creates a string of numbers based on the number of words in a sentence.

I have a variable that contains a varying number of words, eg: sentence="this is a sentence"

The string I need to generate would be "1 2 3 4" as there is 4 words in the sentence.

Similarly, sentence="this is a longer sentence because reasons" would generate "1 2 3 4 5 6 7"

I'm trying something along the lines of this:

SET sentence=this is a longer sentence because reasons
SET count=
SET numbers=1
FOR %%a IN (%sentence%) DO (
  SET "numbers=%numbers% %count%" & SET /A count+=1
)
ECHO Resulting number string: %numbers%
ECHO Counter: %count%

... to keep appending the increasing count variable to the end of number. So each time the FOR loop runs, it goes "1 2", "1 2 3", "1 2 3 4", etc.

The counter is working correctly, reporting "Counter: 7" But the string just reports "Resulting number string: 1 "

It's not adding the counter to the end... and when I have had it append, it results in "1 7" instead of "1 2 3 4 5 6 7"

This is regardless of whether I use setlocal EnableDelayedExpansion or not.

What am I doing wrong here?

(EDIT: This question relates to APPENDING an incrementing number to the end of a string. As I mentioned in my original question, EnableDelayedExpansion make no difference if enabled or disabled)

aschipfl
  • 33,626
  • 12
  • 54
  • 99
Jay Ott
  • 3
  • 2
  • you're not using `delayedexpansion` and a thing or 2 other than that. – Gerhard Feb 05 '19 at 11:35
  • @jeb Edited, as this is not a question about EnableDelayedExpansion. – Jay Ott Feb 05 '19 at 12:07
  • 1
    Your question isn't about delayed expansion, but it's the solution. As `SET "numbers=%numbers% %count%"` can't work in a code block, you have to change it to `SET "numbers=!numbers! !count!"` – jeb Feb 05 '19 at 12:26
  • @jeb unless you do `call SET "numbers=%%numbers%% %%count%%" & SET /A count+=1` – Gerhard Feb 05 '19 at 12:39
  • @GerhardBarnard I try to avoid `call`, as it's slow and has too many other drawbacks – jeb Feb 05 '19 at 12:40
  • @jeb true, not arguing with you, was just mentioning it :) – Gerhard Feb 05 '19 at 12:40

1 Answers1

0

You first preferbly need delayedexpansion as you are setting variables and need to echo inside a code block. Also, you do not need to use 2 different counters:

As per your comment to put in one line:

@echo off
setlocal enabledelayedexpansion
set "sentence=this is a longer sentence because reasons"
set count=
set numbers=
for %%a IN (%sentence%) DO (
 call set "numbers=!numbers!!count!" & set /A count+=1
)
set Resulting number string: %numbers% %count%

and the same, without delayedexpansion, by using call

@echo off
set "sentence=this is a longer sentence because reasons"
set count=
set numbers=
for %%a IN (%sentence%) DO (
 call set "numbers=%%numbers%% %%count%%" & set /A count+=1
)
echo Resulting number string: %numbers% %count%
Gerhard
  • 22,678
  • 7
  • 27
  • 43