title: shell script: nested while loop: not pickup the outer loop counter
body: <p>I have a file that has millions of records.  I will just make it simple with two sample records here.  My goal is to add delimiters, such as a comma, to make the file has the same number of delimiters, so I can upload the file to a database.</p>
  
  <p>The issue is that the nested while loop simply added a fixed number of delimiters at the end of line.  My goal is to add delimiters dynamically according to the number of delimiters the file already has.  I changed the inner while loop to a if statement block, the same behavior happened as well.  So I do not think a nested while loop is necessary.</p>
  
  <p>Here is my sample text file:</p>
  
  <pre><code>1st,1,
  2nd,2
  </code></pre>
  
  <p>Here is the script.  First user input position is the text file, the second position is the number of delimiters I want.</p>
  
  <pre><code>#!/bin/bash
  
  f="$1"
  delim="$2"
  
  while read line
  do
  cnt=`echo $line | tr -cd ',' | wc -c`
      while   [[ $cnt  -lt $delim ]];   
      do
              sed -i 's/$/,/' $f 
          cnt=`expr $cnt + 1`
      done
  done  &lt; $f
  </code></pre>
  
  <p>Here is my trace using bash -x:</p>
  
  <pre><code>bash -x csv.sh split_address_2.csv 3
  + f=split_address_2.csv
  + delim=3
  + read line
  ++ wc -c
  ++ tr -cd ,
  ++ echo 1st,1,
  + cnt=2
  + [[ 2 -lt 3 ]]
  + sed -i 's/$/,/' split_address_2.csv
  ++ expr 2 + 1
  + cnt=3
  + [[ 3 -lt 3 ]]
  + read line
  ++ wc -c
  ++ tr -cd ,
  ++ echo 2nd,2
  + cnt=1
  + [[ 1 -lt 3 ]]
  + sed -i 's/$/,/' split_address_2.csv
  ++ expr 1 + 1
  + cnt=2
  + [[ 2 -lt 3 ]]
  + sed -i 's/$/,/' split_address_2.csv
  ++ expr 2 + 1
  + cnt=3
  + [[ 3 -lt 3 ]]
  + read line
  </code></pre>
  
  <p>Here is the output of the text file.  You can see the script simply added 3 commas at the end of each line.</p>
  
  <pre><code>1st,1,,,,
  2nd,2,,,
  </code></pre>
  
  <p>Thanks so much for your kind response.  Have a good day!</p>