A Scala shell script to insert text before a matching pattern

I don’t remember exactly why I wrote this Scala shell script, but if I remember right I was having a problem getting sed to work properly, so I wrote this little script to insert an Amazon Kindle “break” tag before each <h1> tag in an HTML file:

exec scala -savecompiled "$0" "$@"

import scala.io.StdIn

var line = ""

while ({line = StdIn.readLine(); line != null}) {

    // insert kindle 'break' tag before every h1 tag
    if (line.matches(".*<h1.*")) {
        println("<mbp:pagebreak />")



At the moment I can’t remember what the problem with sed was, but I know that I wrote this script, which I use like this:

cat $FILE | ./InsertBreakB4H1.sh > $TMPFILE

I think part of what I was thinking was that I was getting tired of fighting with sed, and I started wondering if it wouldn’t just be easier to use Scala for filtering/inserting purposes like this.

In summary, if you wanted to see a Scala script that works like sed, I hope this example is helpful.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.