R脚本读取txt文件,查找并替换一些文本,连接结果,然后写入文件

R脚本读取txt文件,查找并替换一些文本,连接结果,然后写入文件

问题描述:

我有一个查询如下。它将一个文本文件读入变量linn。第2行(linn[2])和第28行(linn[28])包含2个日期(20160831; 20160907)。我想循环遍历矢量a并一次复制每个元素,并替换第2行和第8行的值,并创建原始文件的副本,仅更改第2行和第8行。然后我想连接所有的副本并将其写入一个txt文件R脚本读取txt文件,查找并替换一些文本,连接结果,然后写入文件

我怎么能达到相同的?

#http://stackoverflow.com/questions/12626637/reading-a-text-file-in-r-line-by-line 
fileName <- "C:/Users/500361/Downloads/query.txt" 
conn <- file(fileName,open="r") 
linn <-readLines(conn) 
for (i in 1:length(linn)){ 
    print(linn[i]) 
} 
close(conn) 

str(linn) 
linn[2] 
#[1] "<"department_code,department_desc,subclass_code,subclass_desc,dept_rank\" label=\"20160831;20160907\">" 
linn[28] 
#<sel value=\"between(date_id;20160831;20160907) [[ \\ text_req:From \\ text_req:To]] \"/>" 


a=c("20160406;20160413","20160330;20160406") 
a 

更新1:2号线和28更新的值会

"<"department_code,department_desc,subclass_code,subclass_desc,dept_rank\" label=\"20160406;20160413\">" 
     #<sel value=\"between(date_id;20160406;20160413) [[ \\ text_req:From \\ text_req:To]] \"/>" 

"<"department_code,department_desc,subclass_code,subclass_desc,dept_rank\" label=\"20160330;20160406\">" 
     #<sel value=\"between(date_id;20160330;20160406) [[ \\ text_req:From \\ text_req:To]] \"/>" 
+0

请记住包括数据所以我们可以重现这一点(你可以使用'dput()'。这个问题有点不清楚,如果你也提供了一个你想要的结果的例子,这会有所帮助。 –

+0

我已经展示了我想要的结果 – user2543622

+0

你可以用正则表达式来完成,但如果数据是可解析的格式,那就更好了。 – alistaire

我找到了答案,并希望将它张贴对未来的读者

#http://stackoverflow.com/questions/23474552/how-to-read-txt-file-and-replace-word-in-r 

#variable `a` has different set of values that I want to put in my code (find and replace) 
a=c("20160907;20160914","20160831;20160907","20160824;20160831","20160817;20160824","20160810;20160817","20160803;20160810","20160727;20160803","20160720;20160727","20160713;20160720","20160706;20160713","20160629;20160706","20160622;20160629","20160615;20160622","20160608;20160615","20160601;20160608","20160525;20160601","20160518;20160525","20160511;20160518","20160504;20160511","20160427;20160504","20160420;20160427","20160413;20160420","20160406;20160413","20160330;20160406","20160323;20160330","20160316;20160323","20160309;20160316","20160302;20160309","20160224;20160302","20160217;20160224","20160210;20160217","20160203;20160210","20160127;20160203","20160120;20160127","20160113;20160120","20160106;20160113") 

res <- readLines("C:/Users/500361/Downloads/query.txt") 
result=c() 

for (i in 1:36) 
    { 
    #res1 is just copy of the query 
    res1=res 

    #as lines 2 and 28 have the text that I want to replace. I am using gsub function while looping over i 
    res1[2]=gsub(pattern = "20160831;20160907", replace = a[i],x=res1[2]) 
    res1[28]=gsub(pattern = "20160831;20160907", replace = a[i],x=res1[28]) 


    #concatenating results 
    result=c(result,res1) 

    } 



#writing the file 
writeLines(result, con="C:/Users/500361/Downloads/answer.txt")