title: how to edit or modify or change a single line in a large text file with R
body: <p>i'm reading some large text files into databases with R but they contain illegal field names for the database software.  the column names of the large text files are just in the first row -- is it possible to edit only that first row without cycling through every single row in the file (which seems like a waste of resources)?</p>
  
  <p>here are two examples of what i'm trying to do with some example data.  the first reads everything into ram - so that won't work for my large data tables.  the second would work, but it's slow because it processes every line in the file.</p>
  
  <p>i suppose it's important that the solution work across platforms <em>and</em> not require the installation of external software (aside from R packages), just because i'll be sharing this script with others and would rather not ask them to perform more steps than necessary.  i'm looking for the fastest way to do this <em>within R only</em>  :)</p>
  
  <pre><code># create two temporary files
  tf &lt;- tempfile() ; tf2 &lt;- tempfile()
  
  # write the mtcars data table to a file on the disk
  write.csv( mtcars , tf )
  
  # look at the first three lines
  readLines( tf , n = 3 )
  
  # read in the entire table
  z &lt;- readLines( tf )
  
  # make the only substitution i care about
  z[1] &lt;- gsub( 'disp' , 'newvar' , z[1] )
  
  # write the entire table back out to the table
  writeLines( z , tf2 )
  
  # confirm the replacement
  readLines( tf2 , 2 )
  # done!
  
  # # # # # # # OR
  
  # blank out the output file
  file.remove( tf2 )
  
  # create a file connection to the text file
  incon &lt;- file( tf , "r" )
  
  # create a second file connection to the secondary temporary file
  outcon &lt;- file( tf2 , "w" )
  
  # read in one line at a time
  while( length( one.line &lt;- readLines( incon , 1 ) ) &gt; 0 ){
  
      # make the substitution on every line
      one.line &lt;- gsub( 'disp' , 'newvar' , one.line )
  
      # write each line to the second temporary file
      writeLines( one.line , outcon )
  }
  
  # close the connections
  close( incon ) ; close( outcon )
  
  # confirm the replacement
  readLines( tf2 , 2 )
  # done!
  </code></pre>