Home >Backend Development >Golang >How to append to a file before a specific string in go?

How to append to a file before a specific string in go?

王林
王林forward
2024-02-05 21:15:08482browse

How to append to a file before a specific string in go?

Question content

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 text "e" before "//Add more text before this" and "," after "d", so it will be like this:

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

How to implement this dynamically so that more strings can be added to the file in the future?

Thank you


Correct answer


To add the text "e" before the line starting with "//" you can do the following.

  1. Open the file in read/write mode.
  2. Create a scanner based on the file and scan each line into memory.
  3. Check each line while scanning to see if it encounters a line containing "//".
  4. Save each line in an array so it can be written back to the file later.
  5. If the row is found, append the new row "e" and update the previous row.
  6. Write these 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)
    }
}

The above is the detailed content of How to append to a file before a specific string in go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete