title: How to replace a string through grep and perl
body: <p>I wanted to grep a string at the first occurrence ONLY from a file (file.dat) and replace it by reading from another file (output). I have a file called "output" as an example contains "AAA T 0001"</p>
  
  <pre><code>#!/bin/bash
  procdir=`pwd`
  
  cat output | while read lin1 lin2 lin3
  
  do
  
    srt2=$(echo $lin1 $lin2 $lin3 | awk '{print $1,$2,$3}')
  
    grep -m 1 $lin1  $procdir/file.dat | xargs -r0 perl -pi -e 's/$lin1/$srt2/g'
  
  done
  </code></pre>
  
  <p>Basically what I wanted is: </p>
  
  <p>When ever a string "AAA" is grep'ed from the file "file.dat" at the first instance, I want to replace the second and third column next to "AAA" by "T 0001" but still keep the first column "AAA" as it is. Th above script seems not to work. </p>
  
  <p>Basically "$lin1" and $srt2 variables are not understood inside 's/$lin1/$srt2/g'</p>
  
  <p>Example:</p>
  
  <p>in my file.dat I have a row</p>
  
  <pre><code>AAA D ---- CITY COUNTRY
  </code></pre>
  
  <p>What I want is :</p>
  
  <pre><code>AAA T 0001 CITY COUNTRY
  </code></pre>
  
  <p>Any comments are very appreciated.</p>