Search code examples
rtext-files

Searching for string within a text file in R


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?


Solution

  • 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"). Change the path as needed.