Replace nth line in a text file

Simanner picture Simanner · Aug 1, 2012 · Viewed 8k times · Source

How do I go about in replacing the nth line of a text file in R?

Answer

Spacedman picture Spacedman · Aug 1, 2012

To replace the third line of this:

$ cat junk.txt
sic transit
gloria mundi
temeo danoas
et dona ferentes

Do this:

> latin = readLines("junk.txt",-1)
> latin[3]="per ardua ad astra"
> writeLines(latin,"junkout.txt")

and get:

$ cat junkout.txt 
sic transit
gloria mundi
per ardua ad astra
et dona ferentes

You can writeLines(latin,"junk.txt") and overwrite the input file if you want.