Add text to the beginning of a text file without having to copy the entire file into R


I have many large text files, and I would like to add a line at the very beginning. I saw someone had asked this already here. However, this involves reading the entire text file and appending it to the single line. Is there a better (faster) way?

I tested this on windows 7 and it works. Essentially, you use the shell function and do everything on the windows cmd which is quite fast.

write_beginning <- function(text, file){

  #write your text to a temp file i.e. temp.txt
  write(text, file='temp.txt')
  #print temp.txt to a new file
  shell(paste('type temp.txt >' , 'new.txt'))
  #append your file to new.txt
  shell(paste('type', file, '>> new.txt'))
  #remove temp.txt - I use capture output to get rid of the
  #annoying TRUE printed by file.remove
  dump <- capture.output(file.remove('temp.txt'))
  #uncomment the last line below to rename new.txt with the name of your file
  #and essentially modify your old file
  #dump <- capture.output(file.rename('new.txt', file))

#assuming your file is test.txt and you want to add 'hello' at the beginning just do:
write_beginning('hello', 'test.txt')

On linux you just need to find the corresponding command in order to send a file to another one (I really think you need to replace type by cat on linux but I cannot test right now).