[Golang] Insert Line or String to File


Insert a string or line to the position of n-th (0-indexed) line of the file via Golang.

The logic of the code:

  • Read the file line by line into a slice of type string [1].
  • for range the string slice to insert the string to n-th line of the file. Note that line is actually a string with trailing newline '\n'. If you want to insert a line, just append '\n' to the end of the string.

The following is full source code:

utils.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package insert

import (
	"bufio"
	"io"
	"io/ioutil"
	"os"
)

func File2lines(filePath string) ([]string, error) {
	f, err := os.Open(filePath)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	return LinesFromReader(f)
}

func LinesFromReader(r io.Reader) ([]string, error) {
	var lines []string
	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}
	if err := scanner.Err(); err != nil {
		return nil, err
	}

	return lines, nil
}

/**
 * Insert sting to n-th line of file.
 * If you want to insert a line, append newline '\n' to the end of the string.
 */
func InsertStringToFile(path, str string, index int) error {
	lines, err := File2lines(path)
	if err != nil {
		return err
	}

	fileContent := ""
	for i, line := range lines {
		if i == index {
			fileContent += str
		}
		fileContent += line
		fileContent += "\n"
	}

	return ioutil.WriteFile(path, []byte(fileContent), 0644)
}

Usage:

Assume we have a text file named test.txt as follows:

1
2
3
4
5

We want to insert a line with text hello world! to the third line (index 2) of the file. Call InsertStringToFile("test.txt", "hello world!\n", 2)

utils_test.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
package insert

import "testing"

func TestCountLeadingSpace(t *testing.T) {
	err := InsertStringToFile("test.txt", "hello world!\n", 2)
	if err != nil {
		t.Error(err)
	}
}

The result is as follows

1
2
hello world!
3
4
5

Tested on:

  • Ubuntu Linux 16.10
  • Go 1.7.5

References:

[1][Golang] Read Lines From File or String
[2][Golang] Append Line/String to File
[3]

golang insert line - Google search

golang insert line - DuckDuckGo search

golang insert line - Bing search

golang insert line - Yahoo search

golang insert line - Baidu search

golang insert line - Yandex search

[4]

golang insert line to file - Google search

golang insert line to file - DuckDuckGo search

golang insert line to file - Bing search

golang insert line to file - Yahoo search

golang insert line to file - Baidu search

golang insert line to file - Yandex search

[5]insert sting to n-th line of file · siongui/go-rst@3bdfb1a · GitHub