Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to file after match in Kotlin

Tags:

sed

kotlin

New to Kotlin, I'd like to insert a line in the file after a specific match in the file. I know how to do this with sed like the following:

sed "/some line in file/a some text I'd like to add after line" file

But I'd like to understand how I'd go about this in Kotlin. So far I've got got as far as the printWriter interface, but I don't see anything that clearly implies an offset or regex parameter.

So far I've got:

File("file.txt").printWriter(...)

Thanks!

like image 681
ZacAttack Avatar asked Dec 22 '16 08:12

ZacAttack


1 Answers

GNU 'sed' does not insert/remove/update lines in files, it transforms an input stream and provides options for sending the output stream to stdout, to a file, or even to a temporary file which then overwrites the original file after the transformation is complete (this is the --in-place option).

Here is some code that should get you started but note that there are lots of ways to buffer and read/write files, streams, etc.

val file = File("file.txt")
val tempFile = createTempFile()
val regex = Regex("""some line in file""")
tempFile.printWriter().use { writer ->
    file.forEachLine { line ->
        writer.println(when {
            regex.matches(line) -> "a some text I'd like to add after line"
            else -> line
        })
    }
}
check(file.delete() && tempFile.renameTo(file)) { "failed to replace file" }

See also sed, a stream editor for more details on how it transforms text streams.

like image 140
mfulton26 Avatar answered Oct 20 '22 07:10

mfulton26