Replace nth line in a text file

与世无争的帅哥 提交于 2019-12-05 17:02:46

问题


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


回答1:


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.




回答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



来源:https://stackoverflow.com/questions/11756353/replace-nth-line-in-a-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!