Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print the next X number of lines in Scala

Tags:

scala

Trying to learn Scala using the Programming in Scala book and they have a very basic example for reading lines from a file. I'm trying to expand on it and read a file line by line, look for a certain phrase, then print the next 6 lines following that line if it finds the line. I can write the script easily enough in something like java or Perl but I have no idea how to do it in Scala (probably because I'm not very familiar with the language yet...)

Here's the semi adapted sample code from the Programming in Scala book,

import scala.io.Source

if(args.length>0) {
    val lines = Source.fromFile(args(0)).getLines().toList
        for(line<-lines) {
            if(line.contains("secretPhrase")) {
                println(line)
                        //How to get the next lines here?   
            }
        }
}
else
Console.err.println("Pleaseenterfilename")

1 Answers

You could do it similar to how it's done in java

if(args.length > 0) {
  val lines = Source.fromFile(args(0)).getLines.toList
  for(i <- 0 until lines.size) {
    if(lines(i).contains("secretPhrase")) {
      for(j <- i+1 to i+6) println(lines(j))
    }
  }
}

or you use scala idioms to make it shorter

if(args.length > 0) {
  val lines = Source.fromFile(args(0)).getLines
  lines.dropWhile(!_.contains("secretPhrase"))
       .drop(1).take(6).foreach(println)
}
like image 156
SpiderPig Avatar answered Jan 28 '26 19:01

SpiderPig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!