title: Inserting a text into a file, like adding an array element
body: <p>I have a JavaScript <strong>file</strong> like below.</p>
  
  <p><strong>Me.dat</strong></p>
  
  <pre><code>var fruit = [
   "Apple",
   "Mango",
   "Orange"
  ];
  
  var players = [
   "Sachin",
   "Dhoni",
   "Kapil Dev"
  ];
  </code></pre>
  
  <hr>
  
  <p>I would need to dynamically add an element to any of these array.(in the file actually).</p>
  
  <p>Based on a job status, I would insert into the corresponding array.</p>
  
  <p>Say for example,</p>
  
  <pre><code>addMe "Grapes" "fruits"
  </code></pre>
  
  <p>Would create a file,</p>
  
  <pre><code>var fruit = [
   "Apple",
   "Mango",
   "Orange",
   "Grapes" ---------Added newly!!!
  ];
  
  var players = [
   "Sachin",
   "Dhoni",
   "Kapil Dev"
  ];
  </code></pre>
  
  <p>So, I have to insert the text "Grapes" in the 5th line of the file.</p>
  
  <hr>
  
  <p>This is what I have now..</p>
  
  <p><strong>My Script:</strong></p>
  
  <pre><code>SEARCHTERM="fruits";
  TO_BE_ADDED="Grapes";
  #take the start line number and end linenumer of the array..
  startlinenum=`grep -n $SEARCHTERM me.dat | cut -d ":" -f1 | head -1`;
  endlinenum=`tail +$startlinenum me.dat | grep -n "]" | head -1 | cut -d ":" -f1`;
  endlinenum=`expr $startlinenum + $endlinenum - 2`;
  
  echo "\"$TO_BE_ADDED\"" &gt; to_be_added.dat;
  
  echo "ENd line is : ${endlinenum}";
  
  sed "${endlinenum}r to_be_added.dat" me.dat
  </code></pre>
  
  <hr>
  
  <p>I got the <strong>output</strong> as,</p>
  
  <pre><code>var fruits = [
   "Apple",
   "Mango",
   "Orange" ------ How would I remove this Comma ? :(
  "Grapes" ------ Added Correctly....
  ];
  </code></pre>
  
  <hr>
  
  <p>Am I doing a right thing here? Or is there a simpler way around?</p>
  
  <p>Any help please. How would I remove the comma like I mentioned in previous snippet.</p>