比赛结束后在Kotlin中写入文件 [英] Write to file after match in Kotlin
问题描述
Kotlin的新手,我想在文件中的特定匹配项之后在文件中插入一行.我知道如何使用sed进行以下操作:
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
但是我想了解如何在Kotlin进行此操作.到目前为止,我已经了解到了printWriter界面,但是我看不到任何明显暗示offset或regex参数的东西.
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(...)
谢谢!
推荐答案
GNU'sed'不会在文件中插入/删除/更新行,它会转换输入流并提供用于将输出流发送到stdout
的选项,转换为文件,甚至转换为临时文件,然后在转换完成后覆盖原始文件(这是--in-place
选项).
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" }
另请参阅 sed,流编辑器,以了解有关如何操作的更多详细信息它可以转换文本流.
See also sed, a stream editor for more details on how it transforms text streams.
这篇关于比赛结束后在Kotlin中写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!