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
  • 77,979
  • 13
  • 71
  • 125
user1701545
  • 5,110
  • 13
  • 41
  • 77

1 Answers1

15

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").

G. Grothendieck
  • 233,926
  • 16
  • 195
  • 321