SoFunction
Updated on 2025-03-05

Go implements sample code for replacing (overwriting) a certain line of content in a file

1. Preface

There is such a requirement. After we find a line of content with a certain keyword in the file, we replace the content of the line with the new content we need, such as modifying the network configuration file, modifying the image address, modifying all keywords in the code, etc., which is similar to the keyword replacement function in the editor, but we just judge the file directly.

2. Implement the idea of ​​covering a certain line of file content

1. Open the file
2. Read each line of the file
3. Determine whether the line needs to be covered based on the keyword. If yes, write the content from the beginning of the line to overwrite the old content of the line.
Since it is overwrite, we have a prerequisite that the length of the newly written content needs to be greater than or equal to the length of the old content. As for the case where the new content is smaller than the old content, we will try it in the expansion. The basic ideas include two: 1. Write empty content to cover the extra position (it should not work, you can try it); 2. After writing the new content, directly add a new line, and then overwrite the remaining content of the previous file, which is still the idea of ​​overwriting.

3. Implement code examples that cover a certain line of content

Let’s use modifying the network configuration file in my virtual machine as an example to make a simple example (remember to back up first):

The original Ubuntu configuration file content:

$ cat /etc/network/interfaces
# interfaces(5) file used by ifup(8) and ifdown(8)
auto lo
iface lo inet loopback

auto ens33
iface ens33 inet static
address 40.40.40.210
gateway 40.40.40.1
netmask 255.255.255.0

Then we modify the content of the last three lines through keywords such as address, gateway, and netmask to modify the IP address, gateway and subnet mask in the configuration file.

Code content:

package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
    "strings"
)

func main() {
    //Read and write method to open the file    file, err := ("/etc/network/interfaces", os.O_RDWR, 0666)
    if err != nil {
        ("open file filed.", err)
        return
    }
    //defer closes the file    defer ()

    //Get file size    stat, err := ()
    if err != nil {
        panic(err)
    }
    var size = ()
    ("file size:", size)

    //Read the file content into io    reader := (file)
    pos := int64(0)
    ip := "40.40.40.220"
    gateway := "40.40.40.1"
    netmask := "255.255.255.0"
    for {
        //Read each line of content        line, err := ('\n')
        if err != nil {
            //Read to the end            if err ==  {
                ("File read ok!")
                break
            } else {
                ("Read file error!", err)
                return
            }
        }
        (line)

        //Cover the current line according to the keyword        if (line, "address") {
            bytes := []byte("address " + ip + "\n")
            (bytes, pos)
        } else if (line, "gateway") {
            bytes := []byte("gateway " + gateway + "\n")
            (bytes, pos)
        } else if (line, "netmask") {
            bytes := []byte("netmask " + netmask + "\n")
            (bytes, pos)
        }

        //Record position after each line is read        pos += int64(len(line))
    }
}

result:

$ sudo ./go_build_test_go_linux 
[sudo] xx's password:
file size: 180
# interfaces(5) file used by ifup(8) and ifdown(8)

auto lo

iface lo inet loopback

auto ens33

iface ens33 inet static

address 40.40.40.210

gateway 40.40.40.1

netmask 255.255.255.0

File read ok!
$ cat /etc/network/interfaces
# interfaces(5) file used by ifup(8) and ifdown(8)
auto lo
iface lo inet loopback

auto ens33
iface ens33 inet static
address 40.40.40.220
gateway 40.40.40.1
netmask 255.255.255.0

Key point: Record the current moving position for each row read, and then call to write content overwrite (cannot be appended), because when this row is found, the record position is exactly the end of the previous row, so it is just overwrite.

4. Expand

In fact, the most convenient way is actually the shell script method, which can be called through various languages, and sometimes the script can be executed separately.

Secondly, if the new content is less than the length of the old content, it is a little troublesome at this time. When going down the next line or the rest of the content is read and overwrite and write.

If you don’t understand the interface, check the official io package. We will focus on sorting out the interfaces of the io standard library later.

This is the article about Go's example code to implement a certain line of content of a Go file. For more related content of a certain line of content of a certain line of content of Go file, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!