title: Bash: read a file line-by-line and process each segment as parameters to other prog
body: <p>I have some dirty work to do, so a Bash script seems to be a good choice. I'm new to Bash, and the experience makes me kind of frustrated.</p>
  
  <p>The file mapfiles.txt consists of lines as follow. Each line has four segments separated by a white space. Each segment represents a input parameter to an external program name 'prog'. For example, "cm19_1.png" is the <strong>filename</strong>, "0001" the <strong>index</strong>, "121422481" the <strong>longitude</strong>, and "31035995" the <strong>latitude</strong>.</p>
  
  <p>File: mapfiles.txt</p>
  
  <pre><code>cm19_1.png 0001 121422481 31035995
  cm19_2.png 0002 121423224 31035995
  cm19_3.png 0003 121423967 31035995
  …
  </code></pre>
  
  <p>I want to execute similar commands to each line. As show below, the prog's input parameter order is slightly different. So it makes sense to write a bash script to handle the repeated work.</p>
  
  <pre><code>[Usage] prog &lt;index&gt; &lt;longitude&gt; &lt;latitude&gt; &lt;filename&gt;
  example: prog 0001 121422481 31035995 cm19_1.png
  </code></pre>
  
  <p>Generally, the bash script will operate in this way: </p>
  
  <ol>
  <li>Read one line from mapfiles.txt</li>
  <li>Split the segments</li>
  <li>Call the prog with a correct parameter order</li>
  </ol>
  
  <p>Here comes run.sh.</p>
  
  <pre><code>#!/bin/sh
  
  input=mapfiles.txt
  cmd=prog
  
  while read line
  do
          file=$(echo $line | cut -d' ' -f1)
          key=$(echo $line | cut -d' ' -f2)
          log=$(echo $line | cut -d' ' -f3)
          lat=$(echo $line | cut -d' ' -f4)
          echo $cmd $key $log $lat $file
  done &lt; "$input"
  </code></pre>
  
  <p>What I expected is</p>
  
  <pre><code>prog 0001 121422481 31035995 cm19_1.png
  prog 0002 121423224 31035995 cm19_2.png
  prog 0003 121423967 31035995 cm19_3.png
  … 
  </code></pre>
  
  <p>The ACTUAL result I got is</p>
  
  <pre><code> cm19_1.png21422481 31035995
   cm19_2.png21423224 31035995
   cm19_3.png21423967 31035995
  </code></pre>
  
  <p>Problems that confused me</p>
  
  <ol>
  <li>Where is 'prog'? </li>
  <li>Where is the white space?</li>
  <li>What's wrong with the parameter order?</li>
  </ol>
  
  <p>Hmm… I wrote this script on my Mac using vim and copy it to a Scientific Linux box and a gentoo box. These three guys get the same ridiculous outputs.</p>