Question

I have a .txt file that contains a list of menu's and commands. What I want to be able to do is incrementally run through each line of this .txt file, check the number, and increment it from the previous value. So, here is an example section of the file:

menu1=do something
cmd1=cd \\somewhere
menu2=do something
cmd2=cd \\somewhere
menu3=do something
cmd3=cd \\somewhere
menu1=do something
cmd1=cd \\somewhere
menu2=do something
cmd2=cd \\somewhere
menu3=do something
cmd3=cd \\somewhere

Notice how the menu number counts from 1 to 3 then reverts to 1 again halfway through.

Unfortunately, they need to continue incrementing like below.

menu1=do something
cmd1=cd \\somewhere
menu2=do something
cmd2=cd \\somewhere
menu3=do something
cmd3=cd \\somewhere
menu4=do something
cmd4=cd \\somewhere
menu5=do something
cmd5=cd \\somewhere
menu6=do something
cmd6=cd \\somewhere

Is there a way to implement this using a batch file? I am new to this, but parsing the strings, grabbing the number, comparing it to a variable, and then replacing it is proving to be difficult. Could you point me in the right direction? Thank you.

SOLUTION

setlocal DisableDelayedExpansion

set menuNr=1
(
  for /F "tokens=1,2* delims==" %%a in (MyFile.txt) do (
    set "prefix=%%a"
    set "rest=%%b"
    call :processLine
  ) 
)
move /y temp.txt MyFile.txt
exit /b

:processLine
setlocal EnableDelayedExpansion

if "!prefix:~0,4!"=="menu" (
  set "prefix=menu!menuNr!"
)
if "!prefix:~0,3!"=="cmd" (
  set "prefix=cmd!menuNr!"
  set /a menuNr+=1
)

echo !prefix!=!rest! >> temp.txt
(
endlocal
set "menuNr=%menuNr%"
exit /b
)
Was it helpful?

Solution

The first step is to read the file with batch without modifying the content inadvertently.
This can be done with the delayed toggling technic.

Then each line can be checked if it begins with "menu" or "cmd", and create the appropiate menu entry.
After each "cmd"-entry incrementing the menu number.

setlocal DisableDelayedExpansion

set menuNr=1
(
  for /F "tokens=1,2* delims==" %%a in (myMenu.txt) do (
    set "prefix=%%a"
    set "rest=%%b"
    call :processLine
  )
) > temp.txt
exit /b

:processLine
setlocal EnableDelayedExpansion

if "!prefix:~0,4!"=="menu" (
  set "prefix=menu!menuNr!"
)
if "!prefix:~0,3!"=="cmd" (
  set "prefix=cmd!menuNr!"
  set /a menuNr+=1
)

echo !prefix!=!rest!
(
endlocal
set "menuNr=%menuNr%"
exit /b
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top