michaeluskov
michaeluskov

Reputation: 1828

Windows CMD FOR loop

I'm trying to make a code which will get first words from all lines of HELP's output to a variable and echo this variable. Here is my code:

@echo off
set a=
for /F "tokens=1,*" %%i in ('help') do (
set a=%a% %%i 
)
echo %a%

But it returns first word from only last line. Why?

Upvotes: 0

Views: 10029

Answers (3)

dbenham
dbenham

Reputation: 130819

Bali C solved your problem as stated, but it looks to me like you are trying to get a list of commands found in HELP.

Some of the commands appear on multiple lines, so you get some extraneous words. Also there is a leading and trailing line beginning with "For" on an English machine that is not wanted.

Here is a short script for an English machine that will build a list of commands. The FINDSTR command will have to change for different languages.

@echo off
setlocal enableDelayedExpansion
set "cmds="
for /f "eol= delims=." %%A in ('help^|findstr /bv "For"') do (
  for /f %%B in ("%%A") do set "cmds=!cmds! %%B"
)
set "cmds=%cmds:~1%"
echo %cmds%


EDIT

Ansgar Wiechers came up with a more efficient algorithm to extract just the command names at https://stackoverflow.com/a/12733642/1012053 that I believe should work with all languages. I've used his idea to simplify the code below.

@echo off
setlocal enableDelayedExpansion
set "cmds="
for /f %%A in ('help^|findstr /brc:"[A-Z][A-Z]*  "') do set "cmds=!cmds! %%A"
set "cmds=%cmds:~1%"
echo %cmds%

Upvotes: 3

Steve
Steve

Reputation: 216273

Because the echo is outside the do ( ...... )

@echo off
for /F "tokens=1,*" %%i in ('help') do (
echo %%i
)

and no need to print a, you can use directly %%i.
Another very simple example could be a batch like this saved as help1.cmd

@echo off
for /F "tokens=1,*" %%i in ('help') do (
if /I "%%i" EQU "%1" echo %%j
)

and you call this batch like

help1 MKDIR 

to get the short help text for the MKDIR command

Upvotes: 1

Bali C
Bali C

Reputation: 31221

You need to use delayed expansion in your for loop

@echo off
setlocal enabledelayedexpansion
set a=
for /F "tokens=1,*" %%i in ('help') do (
set a=!a! %%i 
)
echo %a%

Instead of using %'s around the a variable, you use !'s to use delayed expansion.

Upvotes: 2

Related Questions