cmd, program generating help-files [closed]

2020-01-20 03:43发布

@echo off
md helpgen 2>nul
cd helpgen
for /F %%i in ('help') do (
  echo %%i|findstr /R "^[A-Z]*$" >nul
  if "%ERRORLEVEL%"=="0" (
    help %%i>%%i.txt
  ) 
)
cd ..

This program is supposed to make help-files for every file from the help command. But... it doesn't work correctly and i have no idea why. help me please)

标签: cmd
2条回答
一夜七次
2楼-- · 2020-01-20 04:04

Your code is not working because %ERRORLEVEL% is expanded at parse time and the entire parenthesized FOR block of code is parsed in one pass. You want the value of ERRORLEVEL for each iteration, but your code is getting the value of ERRORLEVEL that existed before the loop is executed.

One solution is to enable delayed expansion at the top using setlocal enableDelayedExpansion. Then within your loop use !ERRORLEVEL! instead of %ERRORLEVEL%. The delayed expansion will give the desired value of ERRORLEVEL at execution time of each iteration.

Type help set or set /? from the command line to get more information about delayed expansion.

But there is an easier solution that avoids variable expansion all-together. command1 && command2 will execute command2 only if command1 was successful. There is also the || operator to use to execute a command if the prior command was not successful.

But the whole excercise is kind of pointless because your FINDSTR expression will not give the correct results, so your final output will still be wrong.

Ansgar Wiechers identified a search pattern that works in his answer. The "tokens=1" is not needed because that is the default setting.

The final script can be as simple as:

@echo off
md helpgen 2>nul
cd helpgen
for /f %%i in ('help ^| findstr /rc:"^[A-Z][A-Z]*  "') do help %%i>%%i.txt
查看更多
祖国的老花朵
3楼-- · 2020-01-20 04:05

To extract just the commands from the output of help you need something like this:

for /f "tokens=1" %%i in ('help ^| findstr /rc:"^[A-Z][A-Z]*  "') do (
  echo %%i
)

The pattern "^[A-Z][A-Z]* " ensures that you'll only process lines that start with a character and have at least two spaces following the first word.

查看更多
登录 后发表回答