Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading empty values in "for" command in a windows batch file

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?

like image 352
Santhosh Avatar asked Mar 03 '26 21:03

Santhosh


1 Answers

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

like image 104
Dr. belisarius Avatar answered Mar 05 '26 12:03

Dr. belisarius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!