在Golang中替换文本文件中的一行。

huangapple go评论76阅读模式
英文:

Replace a line in text file Golang

问题

如何用新的一行替换文本文件中的一行?

假设我已经打开了文件,并且将每一行都存储在一个字符串对象的数组中,现在我正在循环遍历这些行。

// 寻找包含']'的行
for i, line := range lines {

    if strings.Contains(line, ']') {

        // 用"LOL"替换该行
        lines[i] = "LOL"
    }
}

以上代码将会用"LOL"替换包含']'的行。

英文:

How do I replace a line in a text file with a new line?

Assume I've opened the file and have every line in an array of string objects i'm now looping through

//find line with ']'
	for i, line := range lines {

		if strings.Contains(line, ']') {

             
			//replace line with "LOL"
			?
		}
	}

答案1

得分: 43

这里重要的不是你在循环中做什么。不像你会直接在文件中实时编辑。

对你来说最简单的解决方案就是将数组中的字符串替换,然后在完成后将数组的内容写回文件。

这是我在一两分钟内编写的一些代码。它在我的机器上可以正确编译和运行。

package main

import (
	"io/ioutil"
	"log"
	"strings"
)

func main() {
	input, err := ioutil.ReadFile("myfile")
	if err != nil {
		log.Fatalln(err)
	}

	lines := strings.Split(string(input), "\n")

	for i, line := range lines {
		if strings.Contains(line, "]") {
			lines[i] = "LOL"
		}
	}
	output := strings.Join(lines, "\n")
	err = ioutil.WriteFile("myfile", []byte(output), 0644)
	if err != nil {
		log.Fatalln(err)
	}
}

这里也有一个 gist(包含相同的代码)
https://gist.github.com/dallarosa/b58b0e3425761e0a7cf6

英文:

What matters here is not so much what you do in that loop. It's not like you're gonna be directly editing the file on the fly.

The most simple solution for you is to just replace the string in the array and then write the contents of the array back to your file when you're finished.

Here's some code I put together in a minute or two. It properly compiles and runs on my machine.

package main
 
import (
        "io/ioutil"
        "log"
        "strings"
)
 
func main() {
        input, err := ioutil.ReadFile("myfile")
        if err != nil {
                log.Fatalln(err)
        }
 
        lines := strings.Split(string(input), "\n")
 
        for i, line := range lines {
                if strings.Contains(line, "]") {
                        lines[i] = "LOL"
                }
        }
        output := strings.Join(lines, "\n")
        err = ioutil.WriteFile("myfile", []byte(output), 0644)
        if err != nil {
                log.Fatalln(err)
        }
}

There's a gist too (with the same code)
https://gist.github.com/dallarosa/b58b0e3425761e0a7cf6

huangapple
  • 本文由 发表于 2014年10月2日 08:48:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/26152901.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定