Kotlin新手,我想在文件中的特定匹配后在文件中插入一行.我知道如何使用sed执行此操作,如下所示:
sed "/some line in file/a some text I'd like to add after line" file
Run Code Online (Sandbox Code Playgroud)
但是我想知道我将如何在Kotlin中解决这个问题.到目前为止,我已经得到了printWriter接口,但我没有看到任何明显暗示偏移或正则表达式参数的东西.
到目前为止我有:
File("file.txt").printWriter(...)
Run Code Online (Sandbox Code Playgroud)
谢谢!
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" }
Run Code Online (Sandbox Code Playgroud)
另请参阅sed,一个流编辑器,以获取有关如何转换文本流的更多详细信息.
归档时间: |
|
查看次数: |
842 次 |
最近记录: |