views:

63

answers:

1

I have a question with the "for" batch command in windows.

I have a file called keys.txt which contains this line..

key,value,x86,windows7

I want to parse this line and store the 4 comma seperated variables in 4 variables. I accomplish that by the following windows batch script.

 for /F "tokens=1,2,3,4* delims=," %%i
 in (keys.txt) do (

    echo first is %%i

    echo second is %%j

    echo third is %%k

    echo fourth is %%l

    echo rest is %%m

    echo -------------  

 )

However, when i modify the keys.txt to

key,value,,windows7

The third variable is printed as windows7. I would expect the 3rd variable to be empty and the 4th variable to be windows7. If i give a space between the 2 comma's like this

key,value, ,windows7

Then it prints the 3rd variable as empty and the 4th variable as Windows7.

Anyone knows how i can make the earlier case (i.e the one without the space) also to work correctly?

+3  A: 

Try this. Idea fom here
The script preprocess each line assigning the text #NUL# to each empty slot. You can disregard #NUL# values after that.

cls
setlocal enabledelayedexpansion
@echo off
for /f "tokens=*" %%X in (keys.txt) do (
    set "work=%%X"
    :: fill empty fields with "#NUL#" ...
    :: but do it twice, just in case consecutive fields are empty
    for /l %%i in (1,1,2) do set "work=!work:,,=,#NUL#,!"
    for /F "tokens=1,2,3,4* delims=," %%i in ("!work!") do (
echo first is %%i
echo second is %%j
echo third is %%k
echo fourth is %%l
echo rest is %%m
echo -------------  
))

HTH

belisarius
Thank you so much!!!It works like a breeze!
Santhosh