Extreme Java When vanilla Java is not enough

10May/101

sed-like function in scala

It was a long time without using Scala, but I had a problem that it solved like a charm. I need to edit a huge file with one XML per line, replacing "b" for "bb" (i.e. duplicate a tag). I could do it with a single SED command, but, on an Windows box, I used this scala script:

def solveMyProblem = {
  import java.io.File
  import scala.io.Source
 
  Source.fromFile(new File("path-to-file"))
    .getLines()
    .map {
      _.replaceAll("(<a>(.*)</a>)", "$1<c>$2</c>");
    }
    .foreach {
      Console.println(_)
    }
}

I'm still using Scala 2.7, but this got my problem solved. It was easy to test - instead of thousands of lines on my Console, I put a ".take(10)" and I got something like Linux's "sed | head".

BTW, I guess it could be improved even more, but I don't have time to do that too.

Tagged as: , , 1 Comment