Searching for string within a text file in R [clos

2019-02-14 20:07发布

问题:

Is there an R function that would search for s string within a text file? Something like unix grep?

I guess the alternative will be to read the file line by line but was wondering if that can be bypassed by such a function?

回答1:

1) Read it in and use R's grep:

 # test input
 cat("a 1\n\b 2\nc 3\n", file = "myfile.dat")


 grep("a", readLines("myfile.dat"), value = TRUE)
 ## [1] "a 1"

2) Another possibility if you have grep on your system and on the search path is:

 shell("grep a myfile.dat")
 ## a 1

On Windows you could use findstr in place of grep or if you have Rtools installed but not on your path shell("C:\\Rtools\\bin\\grep a myfile.dat").



标签: r text-files