Suppose that "text.txt" is one of your text files. Read in R with readLines , you can use grep to find a line containing SEN SLOPE . Without additional arguments, grep returns the index number (s) for the element in which the regular expression was found. Here we find that this is the 11th line. Add value = TRUE to get the row as it reads.
x <- readLines("text.txt") grep("SEN SLOPE", x) ## [1] 11 ( gg <- grep("SEN SLOPE", x, value = TRUE) ) ## [1] "SEN SLOPE = .24"
To find all .txt files in the working directory, we can use list.files with a regular expression.
list.files(pattern = "*.txt") ## [1] "text.txt"
RECORDING ON SEVERAL FILES
I created a second text file text2.txt with a different SEN SLOPE value to illustrate how I can apply this method to multiple files. We can use sapply and then strsplit to get the required spl values.
GG <- list.files(pattern = "*.txt") S <- sapply(seq_along(GG), function(i){ X <- readLines(GG[i]) ifelse(length(X) > 0, grep("SEN SLOPE", X, value = TRUE), NA) ## added 04/23/14 to account for empty files (as per comment) }) spl <- unlist(strsplit(S, split = ".*((=|(\\s=))|(=\\s|\\s=\\s))")) ## above regex changed to capture up to and including "=" and ## surrounding space, if any - 04/23/14 (as per comment) SenStat <- as.numeric(spl[nzchar(spl)])
Then we can put the results in a data frame and send it to a file using write.table
( SenStatDf <- data.frame(SenStat, file = GG) )
We can write it to a file using
write.table(SenStatDf, "myFile.csv", sep = ", ", row.names = FALSE)
UPDATED 07/21/2014:
Since the result is written to a file, this can be made much simpler (and faster) with
( SenStatDf <- cbind( SenSlope = c(lapply(GG, function(x){ y <- readLines(x) z <- y[grepl("SEN SLOPE", y)] unlist(strsplit(z, split = ".*=\\s+"))[-1] }), recursive = TRUE), file = GG ) ) # SenSlope file # [1,] ".46" "test2.txt" # [2,] ".24" "test.txt"
And then it is written and read in R with
write.table(SenStatDf, "myFile.txt", row.names = FALSE) read.table("myFile.txt", header = TRUE) # SenSlope file # 1 1.24 test2.txt # 2 0.24 test.txt