Replace nth line in a text file
Asked Answered
B

2

13

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

Benue answered 1/8, 2012 at 9:26 Comment(4)
Have you looked at help(readLines)?Beano
Welcome to Stack Overflow! To the person who silently downvoted: This is the summer of love, so I suggest you do one of a few things 1) Explain why the downvote, 2) Explain to the OP how to improve the question 3) Edit the question so it is a good question.Gnostic
Thanks for the explanation. I had looked at readLines but I did not know about writeLines.Benue
@Simanner: I recommend you always read the "See Also" section of the help pages. Had you read the "See Also" section of ?readLines, you would have seen writeLines.Ballplayer
B
28

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.

Beano answered 1/8, 2012 at 9:47 Comment(0)
L
2

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

Lightfingered answered 1/8, 2012 at 9:33 Comment(1)
Please be careful when posting answers. R is case-sensitive, so readlines is not the same as readLines, and there is actually a function readline.Thew

© 2022 - 2024 — McMap. All rights reserved.