4

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?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
user1701545
  • 5,706
  • 14
  • 49
  • 80

1 Answers1

16

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.

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341