sed-like function in scala
Monday, May 10th, 2010It 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 “<a>b</a>” for “<a>b</a><c>b</c>” (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.