title: sed second occurrence of a string - for all lines in external file (Linux)
body: <p>I have a file that has duplicate values in column 2 that need to be renamed. There are ~8k duplicate values (in file <strong>list.of.duplicates</strong>) throughout the ~5m line file (<strong>with.duplicates</strong>).</p>
  
  <h2>Data set inputs:</h2>
  
  <p><strong>with.duplicates</strong></p>
  
  <p>1       rs143225517     0       751756  C       T</p>
  
  <p>1       rs146277091     0       752478  A       G</p>
  
  <p>1       rs3094315       0       752566  G       A</p>
  
  <p>1       rs149886465     0       752617  A       C</p>
  
  <p>1       <strong>rs3131972</strong>       0       752721  A       G</p>
  
  <p>1       <strong>rs3131972</strong>       0       752721  AT      G</p>
  
  <p>1       rs3131971       0       752894  T       C</p>
  
  <p>1       rs61770173      0       753405  C       A</p>
  
  <p>1       rs2073814       0       753474  C       G</p>
  
  <p>1       rs2073813       0       753541  A       G</p>
  
  <p>1       rs12184325      0       754105  T       C</p>
  
  <p><strong>list.of.duplicates</strong></p>
  
  <p>rs3131972</p>
  
  <p>rs4310388</p>
  
  <p>rs7529459</p>
  
  <p>rs905135</p>
  
  <p>rs9786995</p>
  
  <p>rs12065710</p>
  
  <p>rs6426404</p>
  
  <p>rs12759849</p>
  
  <p>rs6603823</p>
  
  <h2>Code I tried</h2>
  
  <p>This does exactly what I want - but inefficiently and for only one substitution</p>
  
  <pre><code>sed -i '0,/rs3131972/! s/rs3131972/qrs3131972/' with.duplicates
  </code></pre>
  
  <p>But I can't figure out how to iterate through the entire list of duplicate values</p>
  
  <pre><code>i=0 
  while ((i++)); 
  read -r snp 
  do 
  sed -i '0,/${snp}/! s/${snp}/q${snp}/' with.duplicates 
  done &lt; list.of.duplicates
  </code></pre>
  
  <p>I've found partial answers throughout the site but none that get everything together into an efficient script. </p>
  
  <p>Thanks in advance for any help!</p>
  
  <p>Looking for a solution in Linux or R</p>
  
  <p>edit:</p>
  
  <p><strong>Desired output</strong></p>
  
  <p>1       rs143225517     0       751756  C       T</p>
  
  <p>1       rs146277091     0       752478  A       G</p>
  
  <p>1       rs3094315       0       752566  G       A</p>
  
  <p>1       rs149886465     0       752617  A       C</p>
  
  <p>1       <strong>rs3131972</strong>       0       752721  A       G</p>
  
  <p>1       <strong>qrs3131972</strong>       0       752721  AT      G</p>
  
  <p>1       rs3131971       0       752894  T       C</p>
  
  <p>1       rs61770173      0       753405  C       A</p>
  
  <p>1       rs2073814       0       753474  C       G</p>
  
  <p>1       rs2073813       0       753541  A       G</p>
  
  <p>1       rs12184325      0       754105  T       C</p>