Skip to content

Instantly share code, notes, and snippets.

@olih
Created April 11, 2013 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olih/5363903 to your computer and use it in GitHub Desktop.
Save olih/5363903 to your computer and use it in GitHub Desktop.
Searches for files in a directory hierarchy matching a given pattern
import scala.xml._
import scala.xml.transform._
import java.io.File
import scala.util.matching.Regex
import scala.util.matching.Regex.Match
/**
Creator: 2013, Olivier Huin (https://github.com/olih)
License: Eclipse Public License - v 1.0
Contributors:
*/
object FileSearch {
object Meta {
val description = "Searches for files in a directory hierarchy matching a given pattern"
val signature = "FileSearch.process(idirectory: String, filterRegex: scala.util.matching.Regex)"
val parameters = Array(
"idirectory: the directory to start the search from.",
"filterRegex: a pattern which needs to be found in the files to be processed")
val creator = "Olivier Huin (https://github.com/olih)"
val license = "Eclipse Public License - v 1.0"
val copyrightYear = 2013
val keywords="file"
val version="1.15"
val usage = s"""
Usage: $signature
$description
* ${parameters(0)}
* ${parameters(1)}
Creator: $copyrightYear, $creator
License: $license
Keywords: $keywords
Version: $version
"""
}
def process(idirectory: String, filterRegex: scala.util.matching.Regex): Array[File] = {
require(idirectory!=null, {println("You must provide a directory to search from !")})
require(filterRegex!=null, {println("You must provide a regular expression for searching !")})
val inputDir = new File(idirectory)
require(inputDir.exists(),{println(s"The given directory does not exist! $inputDir \n")})
require(inputDir.isDirectory(),{println(s"The parameter is not a directory ! $inputDir \n")})
val allfiles = recursiveListFiles(inputDir)
val r = allfiles.filter(f => filterRegex.pattern.matcher(f.getName).find && f.isFile)
return r
}
def recursiveListFiles(f: File): Array[File] = {
val these = f.listFiles
these ++ these.filter(_.isDirectory).flatMap(recursiveListFiles)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment