用golang实现了某个文件中字符的替换,替换为按行替换,执行后会生成新文件,如a.txt,执行后生成a.txt.mdf。新文件即修改后的内容。

主要用来练习文件的读取与写入

package main 
import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"
)
 
func main() {
	if len(os.args) != 4 {
		fmt.println("lack of config file, eg: go run main.go ${path_of_file} ${old_string} ${new_string}")
		os.exit(-1)
	}
	filename := os.args[1]
	in, err := os.open(filename)
	if err != nil {
		fmt.println("open file fail:", err)
		os.exit(-1)
	}
	defer in.close()
 
	out, err := os.openfile(filename+".mdf", os.o_rdwr|os.o_create, 0766)
	if err != nil {
		fmt.println("open write file fail:", err)
		os.exit(-1)
	}
	defer out.close()
 
	br := bufio.newreader(in)
	index := 1
	for {
		line, _, err := br.readline()
		if err == io.eof {
			break
		}
		if err != nil {
			fmt.println("read err:", err)
			os.exit(-1)
		}
		newline := strings.replace(string(line), os.args[2], os.args[3], -1)
		_, err = out.writestring(newline + "\n")
		if err != nil {
			fmt.println("write to file fail:", err)
			os.exit(-1)
		}
		fmt.println("done ", index)
		index++
	}
	fmt.println("finish!")
}

执行结果:

源文件:

将空格替换为逗号:

新文件:

补充:golang关于字符串替换的建议

运行下面一段代码

package main
import (
 "fmt"
 "regexp"
)
func main() {
 tmp := "/users/max/downloads/test/website\\nbackup\n"
 buf := []byte(tmp)
 a := "/users/max/downloads/test/website\\nbackup"
 r := regexp.mustcompile(a + "\n")
 tasktext := r.replaceallstring(string(buf[:]), "")
 fmt.println(r.string() == string(buf[:]))
 fmt.printf("%q\n", r.string())
 fmt.printf("%q\n", string(buf[:]))
 fmt.printf("%q\n", tasktext)
}

结果输出:

true

“/users/max/downloads/test/website\\nbackup\n”

“/users/max/downloads/test/website\\nbackup\n”

“/users/max/downloads/test/website\\nbackup\n”

可以发现,字符串并没有被替换

然后,我们更改一句代码

package main
import (
 "fmt"
 "regexp"
 "strings"
)
func main() {
 tmp := "/users/max/downloads/test/website\\nbackup\n"
 buf := []byte(tmp)
 a := "/users/max/downloads/test/website\\nbackup"
 r := regexp.mustcompile(a + "\n")
 // tasktext := r.replaceallstring(string(buf[:]), "")
 tasktext := strings.replaceall(string(buf[:]), r.string(), "")
 fmt.println(r.string() == string(buf[:]))
 fmt.printf("%q\n", r.string())
 fmt.printf("%q\n", string(buf[:]))
 fmt.printf("%q\n", tasktext)
}

结果输出:

true

“/users/max/downloads/test/website\\nbackup\n”

“/users/max/downloads/test/website\\nbackup\n”

“”

可以发现,字符串可以被替换

所以,建议在使用字符串替换时,避免使用正则表达式的replaceallstring方法,而应该选择更为稳妥的strings包中的replaceall方法。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。如有错误或未考虑完全的地方,望不吝赐教。