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.
- Open the file in read/write mode.
- Create a scanner from the file, and scan each line into memory.
- Check each line as you scan to see if you come across the line containing "//".
- Save each line in an array so that they can be written back to the file later.
- If you find that line, then append your new line, "e", and update the previous line.
- 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)
}
}