Home > Article > Backend Development > How to append to a file before a 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 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
To add the text "e" before the line starting with "//" you can do the following.
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!