Split string line read by a batch file

16,902

Yes, this can be done. A special FOR syntax is used

for /F "delims=," %A in (filename.txt) do call subbatch.bat %A %B %C %D %E

That'll split it just on a comma. But by default it'll split on space and tab. the 'tokens' term can specify how many of those you want to deal with

for /F "tokens=1,2,3,*" %A in (filename.txt) do call subbatch.bat %A %B %C "%D"

In this case %D will contain everything from the fourth delim and beyond.

The thing to keep in mind, though, is that "Do" is not a procedure block, it's a one-off call. This is where "goto" or "call" can be used to invoke further logic. My examples above call another batch-file and pass in the needed parameters as command-line options, so for those subbatch files the variables will be on %1 and %2.

Share:
16,902
stighy
Author by

stighy

Updated on September 18, 2022

Comments

  • stighy
    stighy almost 2 years

    is there a way to "split" the value of string line readed by a batch file ? Suppose to have this text file

    192.168.1.2; PC_NAME_1

    192.168.1.3; PC_NAME_3

    ...

    I would like to read line 1, and split the value into two variables ... So i can use IP address, and also, Pc Name (for other purpose)... for example:

    for /f %%x in (txtfile.txt) do ( ....

    Thanks

  • CoveGeek
    CoveGeek over 8 years
    You should not use goto after DO or it will break the loop. You are correct about using Call though. @Joey You are correct about using ( <code> ) after the DO block as long as the ( starts on the same line right after the DO. You can also CALL :label to run a sub-procedure within the same batch file.