Skip to content

Instantly share code, notes, and snippets.

@robbypelssers
Last active December 19, 2015 22:39
Mimicking grep command in Scala
package implicits
import java.io.File
import scala.io.Source
object RichFileDemo {
class RichFile(file: String) {
def matchLines(source: Source, pattern: String): Iterator[(String, Int)] = {
source.getLines.zipWithIndex.filter(l => pattern.r.findFirstIn(l._1) != None)
}
def grep(pattern: String): Unit = {
val source = Source.fromFile(file)
matchLines(source,pattern).foreach(x => println("line " + x._2 + ": " + x._1))
source.close
}
}
def main(args: Array[String]): Unit = {
val file = new RichFile("c:/scalademo/news.txt")
file.grep("com")
}
}
//news.txt
/**
Working together with leaders of the Play Framework, Akka, and Scala open source communities,
Typesafe seeks to give developers the modern tools they need to build the next generation of
software applications for the era of multicore hardware and cloud computing workloads.
**/
//output program
/**
line 0: Working together with leaders of the Play Framework, Akka, and Scala open source communities,
line 2: software applications for the era of multicore hardware and cloud computing workloads.
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment