Reputation: 177
I am running RStudio 3.2.3 on Windows 7. I need to read certain text in a text file. The code below successfully appends from line 1 to 24 in the original file to the new file. The lines I need to append into the new file always starts with "DATE ACQUIRED = ". Can I search for that line (line 23), just read the date on it, and append the date to the file? If I could append it to a spreadsheet that would be great.
con <- file("LC80140332015238LGN00_MTL.txt")
x <- readLines(con,24)
unlink("data")
write(x,file="myMTLfile2.txt",append=TRUE)[/CODE]
Upvotes: 0
Views: 1078
Reputation: 3648
Simple parsing using grep
and sub
should work just fine
lines <- readLines("LC80140332015238LGN00_MTL.txt")
# get lines with DATE_ACQUIRED
matched_lines <- lines[which(grepl("DATE_ACQUIRED", lines))]
# extract date
date_acquired <- sub(".*(\\d{4}-\\d{2}-\\d{2}).*", "\\1", matched_lines)
write(date_acquired, "myMTLfile2.txt", append=TRUE)
You might need to change the regex for date parsing if you have dates in different formats.
Upvotes: 1