Reputation: 1925
I have a file.txt like this that I want to read in R until some match is found:
header1
header2
more descriptions
again
stop here
dataline1
dataline2
dataline3
in this case the match would be "stop here".
I want to do this the following way:
x<-file("file.txt","r")
match<-paste("stop","here")
line<-readLines(x,1)
while(line!=match){
line<-readLines(x,1)
}
line
[1] "stop here"
The problem is that the stopping line can have more strings, that is, besides "stop here" can be like "stop here something", where something can change from file to file. When trying to read this new file with the code above it throws an error:
Error in while (line != match) { : argument is of length zero
and line is empty.
line
character(0)
I've tried using collapse and grep, but with the same error.
match<-paste("stop","here", collapse = "|")
while(line!=grep(match, line)){
Is there any way to work around this? Thanks
Upvotes: 3
Views: 1425
Reputation: 18437
You can use grepl
instead of grep
since it returns directly a logical
x <- file("file.txt", "r")
line <- readLines(x, 1)
while(!grepl("^stop here.+", line)) {
line <- readLines(x, 1)
}
Upvotes: 3