Scala : cleanest way to recursively parse files checking for multiple strings

Posted by fred basset on Stack Overflow See other posts from Stack Overflow or by fred basset
Published on 2011-01-07T20:27:51Z Indexed on 2011/01/07 21:53 UTC
Read the original article Hit count: 184

Filed under:
|
|

Hi All,

I want to write a Scala script to recursively process all files in a directory. For each file I'd like to see if there are any cases where a string occurs at line X and line X - 2. If a case like that occurs I'd like to stop processing that file, and add that filename to a map of filenames to occurrence counts. I just started learning Scala today, I've got the file recurse code working, and need some help with the string searching, here's what I have so far:


import java.io.File
import scala.io.Source

val s1= "CmdNum = 506"
val s2 = "Data = [0000,]"

def processFile(f: File) {
  val lines = scala.io.Source.fromFile(f).getLines.toArray
  for (i = 0 to lines.length - 1) {
    // want to do string searches here, see if line contains s1 and line two lines above also contains s1
    //println(lines(i))
  }
}

def recursiveListFiles(f: File): Array[File] = {
  val these = f.listFiles
  if (these != null) {
    for (i = 0 to these.length - 1) {
      if (these(i).isFile) {
        processFile(these(i))
      }
    }
    these ++ these.filter(_.isDirectory).flatMap(recursiveListFiles)
  }
  else {
    Array[File]()
  }
}

println(recursiveListFiles(new File(args(0))))

© Stack Overflow or respective owner

Related posts about string

Related posts about file