[英]How to append to file before specific string in go?
我有一个以此结构开头的文件:
locals {
MY_LIST = [
"a",
"b",
"c",
"d"
//add more text before this
]
}
我想在“//在此之前添加更多文本”之前添加文本“e”,在“d”之后添加“,”,这样他就会像这样:
locals {
MY_LIST = [
"a",
"b",
"c",
"d",
"e"
//add more text before this
]
}
我怎样才能动态地实现它,以便将来可以向文件中添加更多字符串?
谢谢
要在以“//”开头的行之前添加文本“e”,您可以这样做。
func main() {
f, err := os.OpenFile("locals.txt", os.O_RDWR, 0644)
if err != nil {
log.Fatal(err)
}
scanner := bufio.NewScanner(f)
lines := []string{}
for scanner.Scan() {
ln := scanner.Text()
if strings.Contains(ln, "//") {
index := len(lines) - 1
updated := fmt.Sprintf("%s,", lines[index])
lines[index] = updated
lines = append(lines, " \"e\"", ln)
continue
}
lines = append(lines, ln)
}
content := strings.Join(lines, "\n")
_, err = f.WriteAt([]byte(content), 0)
if err != nil {
log.Fatal(err)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.