Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace nth line in a text file

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

like image 522
Simanner Avatar asked Aug 01 '12 09:08

Simanner


People also ask

How do I replace a string in a file?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.


2 Answers

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.

like image 75
Spacedman Avatar answered Oct 18 '22 20:10

Spacedman


I don't know if there is an option to change a specific line in the streaming file (seek in file), although you have the option to read the file , change a column and write the the frame to a file, read, write functions supply you what you need.

You may also use read.table() to read the file into a table format, change specific row and then write.table()

you have options like read.csv() and write.csv() and many other options like readLines().

EDIT

Here is a wiki link for file handling in R

like image 2
Michael Avatar answered Oct 18 '22 20:10

Michael