Kotlin中匹配后写入文件

7

如果您刚接触Kotlin,想在文件中特定匹配项后插入一行内容。我知道可以使用sed完成以下操作:

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

但我希望了解如何在Kotlin中实现这一点。到目前为止,我已经使用了printWriter接口,但我没有看到任何明确暗示偏移量或正则表达式参数的内容。

到目前为止,我已经完成了以下工作:

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

谢谢!

1个回答

7

GNU 'sed'并不会在文件中插入/删除/更新行,它可以转换输入流,并提供选项将输出流发送到stdout、文件甚至是一个临时文件,完成转换后覆盖原始文件(这是--in-place选项)。

以下是一些代码,应该能帮助您入门,但请注意有许多方法可以缓冲和读写文件、流等。

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" }

此外,有关如何转换文本流的更多详细信息,请参见流编辑器sed


啊!我就猜想可能是这样的事情。谢谢! - ZacAttack

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接