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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With