title: Use batch scripting to replace null values with 0 in a specific column in a CSV
body: <p>I need to prepare an automatically-generated CSV file for import into a database. One of the columns is supposed to contain integers, but the generating program (which I have no control of) doesn't always put anything in that column. The database import won't accept null values in an integer column. There are other string columns that should stay null.</p>
  
  <p>Here's a simplified CSV with the problem:</p>
  
  <pre><code>"UID","Name","Comment","LicenseNo","DateEntered"
  "1","Adam","Likes puppies","4451","2014-05-01"
  "2","Barbara","","",2014-05-02"
  "3","","Reserved","","2014-05-03"
  "4","Donna","","4559","2014-05-04"
  </code></pre>
  
  <p>I'd like to replace the <code>""</code> occurrences with <code>"0"</code> in column 4 <strong>only</strong>.</p>
  
  <p>I can get as far as being able to isolate the column in each row and set a non-nil substitute variable:</p>
  
  <pre><code>set inputCSV=%1
  set outputCSV=%2
  
  for /f "delims==" %%a IN (%inputCSV%) DO (
      set line=%%a
      for /f "tokens=4 delims=," %%b IN ("!line!") DO (
          if %%b=="" (
              set data="0"
          ) else (
              set data=%%b
          )
      )
  )
  </code></pre>
  
  <p>However, I can't figure out how to output the corrected line to a new file. I was heading towards inserting something like:</p>
  
  <pre><code>if !data!=="0" (
  for /f "tokens=1-3 delims=," %%d IN ("!line!") DO set prev=%%d,%%e,%%f
  for /f "tokens=5 delims=," %%g IN ("!line!") DO set next=%%g
  echo !prev!,!data!,!next! &gt;&gt; %outputCSV%
  ) else (
  echo !line! &gt;&gt; %outputCSV%
  )
  </code></pre>
  
  <p>But the real CSV has dozens of columns, so I'm going to run out of FOR variables, and it just seems like there's a better way I can't see ...</p>
  
  <p>Any insight would be appreciated.</p>