Skip to content

Instantly share code, notes, and snippets.

@takungsk
Created May 6, 2012 11:40
Show Gist options
  • Save takungsk/2621809 to your computer and use it in GitHub Desktop.
Save takungsk/2621809 to your computer and use it in GitHub Desktop.
テキスト読み込み2
// Scala 実践プログラミングの grep の記事を参考にしたバージョン
import scala.io.Source
object CheckLog {
case class Args(
filename: String,
exp: String
)
def main(args: Array[String]) {
val argsOption = parseArgs(args.toList)
val s = Source.fromFile(argsOption.get.filename,"UTF8")
val exp = argsOption.get.exp
val p = exp.r
try {
val lines = s.getLines.takeWhile(_ != null).toList
val linesWithNum = lines.zipWithIndex.map{ case(line,i) => (i + 1, line) }
val result = linesWithNum.filter{ case(_, line) => line.matches(exp) }
for((lnum, line) <- result) printf("%d: %s %s%n", lnum, line, p.findFirstMatchIn(line).get.matched)
printf("matched = %d%n", result.length)
} finally {
s.close
}
}
def parseArgs(args: List[String]): Option[Args] = {
var fileName = "./takuya71.log"
var exp = ".*error|hoge"
@scala.annotation.tailrec
def parseArgsHelper(args: List[String]): Args = {
args match {
case "-f" :: x :: rest => {
fileName = x
parseArgsHelper(rest)
}
case "-e" :: x :: rest => {
exp = x
parseArgsHelper(rest)
}
case _ => Args(fileName,exp)
}
}
try {
Some(parseArgsHelper(args))
}
catch {
case _ => None }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment