简体   繁体   English

如何在特定字符串之前追加到文件?

[英]How to append to file before specific string in go?

I have a file that starts with this structure:我有一个以此结构开头的文件:

locals {
  MY_LIST = [
    "a",
    "b",
    "c",
    "d"
    //add more text before this
  ]
}

I want to add in the text "e" before the "//add more text before this" and "," after the "d" so he will be like this:我想在“//在此之前添加更多文本”之前添加文本“e”,在“d”之后添加“,”,这样他就会像这样:

locals {
  MY_LIST = [
    "a",
    "b",
    "c",
    "d",
    "e"
    //add more text before this
  ]
}

how can I implement this dynamically so that I can add more strings to the file in the future?我怎样才能动态地实现它,以便将来可以向文件中添加更多字符串?

Thanks谢谢

To add the text "e" before the line beginning with "//" you can do something like this.要在以“//”开头的行之前添加文本“e”,您可以这样做。

  1. Open the file in read/write mode.以读/写模式打开文件。
  2. Create a scanner from the file, and scan each line into memory.从文件创建扫描仪,并将每一行扫描到内存中。
  3. Check each line as you scan to see if you come across the line containing "//".扫描时检查每一行,看看是否遇到包含“//”的行。
  4. Save each line in an array so that they can be written back to the file later.将每一行保存在一个数组中,以便稍后可以将它们写回到文件中。
  5. If you find that line, then append your new line, "e", and update the previous line.如果找到该行,则附加新行“e”并更新上一行。
  6. Write the lines back to the file.将行写回文件。
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM