Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prepend to a file (add at the top)

Imagine you have a file

sink("example.txt")
data.frame(a = runif(10), b = runif(10), c = runif(10))
sink()

and would want to add some header information, like

/* created on 31.3.2011 */
/* author */
/* other redundant information */

How would I add this "header"? Doing it manually seems trivial. Hit a few Enters, copy/paste or write information and you're done. Of course, in R, I could read in example.txt, create example2.txt, add header information and then example.txt.

I was wondering if there's another way of appending files from the "top". Other solutions (from c++ or Java...) also welcome (I'm curious how other languages approach this problem).

like image 476
Roman Luštrik Avatar asked Mar 31 '11 13:03

Roman Luštrik


3 Answers

in R there is no need to work with an extra file. You can just do :

writeLines(c(header,readLines(File)),File)

Yet, using the linux shell seems the most optimal solution, as R is not famous for performant file reading and writing. Especially not since you have to read in the complete file first.

Example :

Lines <- c(
"First line",
"Second line",
"Third line")
File <- "test.txt"
header <- "A line \nAnother line \nMore line \n\n"

writeLines(Lines,File)
readLines(File)    

writeLines(c(header,readLines(File)),File)
readLines(File)
unlink(File)
like image 85
Joris Meys Avatar answered Nov 19 '22 19:11

Joris Meys


It is totally easy in the linux shell:

echo 'your additional header here' >> tempfile
cat example.tst >> tempfile
mv tempfile example
rm tempfile
like image 6
tgmath Avatar answered Nov 19 '22 18:11

tgmath


In any language there is ultimately only one solution. And that is to overwrite the whole file:

contents = readAllOf("example.txt")

overwrite("example.txt", header + contents )
like image 5
Gareth Davis Avatar answered Nov 19 '22 20:11

Gareth Davis