gpt4 book ai didi

sed - 在 Kotlin 中匹配后写入文件

转载 作者:行者123 更新时间:2023-12-04 11:48:27 25 4
gpt4 key购买 nike

Kotlin 的新手,我想在文件中的特定匹配之后在文件中插入一行。我知道如何使用 sed 执行此操作,如下所示:

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

但我想了解如何在 Kotlin 中解决这个问题。到目前为止,我已经了解了 printWriter 接口(interface),但我没有看到任何明确暗示偏移量或正则表达式参数的东西。

到目前为止,我有:
File("file.txt").printWriter(...)

谢谢!

最佳答案

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, a stream editor有关它如何转换文本流的更多详细信息。

关于sed - 在 Kotlin 中匹配后写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41278921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com