Home > Net >  How to append to file before specific string in go?
How to append to file before specific string in go?

Time:12-22

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:

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

CodePudding user response:

To add the text "e" before the line beginning with "//" you can do something like this.

  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.
  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)
    }
}
  •  Tags:  
  • go
  • Related