加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

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

发布时间:2020-12-14 01:02:49 所属栏目:Linux 来源:网络整理
导读:Kotlin新手,我想在文件中的特定匹配后在文件中插入一行.我知道如何使用sed执行此操作,如下所示: sed "/some line in file/a some text I'd like to add after line" file 但是我想知道我将如何在Kotlin中解决这个问题.到目前为止,我已经得到了printWriter接
Kotlin新手,我想在文件中的特定匹配后在文件中插入一行.我知道如何使用sed执行此操作,如下所示:

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

但是我想知道我将如何在Kotlin中解决这个问题.到目前为止,我已经得到了printWriter接口,但我没有看到任何明显暗示偏移或正则表达式参数的东西.

到目前为止我有:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读