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

王林
Release: 2024-02-05 21:15:08
forward
435 people have browsed it

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
  ]
}
Copy after login

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
  ]
}
Copy after login

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)
    }
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!