用golang如何替换某个文件中的字符串
程序员文章站
2022-03-03 11:08:17
用golang实现了某个文件中字符的替换,替换为按行替换,执行后会生成新文件,如a.txt,执行后生成a.txt.mdf。新文件即修改后的内容。主要用来练习文件的读取与写入package main i...
用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方法。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。
下一篇: 银耳汤要熬多长时间
推荐阅读
-
企业案例:查找当前目录下所有文件,并把文件中的https://www.cnblogs.com/zhaokang2019/字符串替换成https://www.cnblogs.com/guobaoyan2019/
-
模板字符串替换教程,实现一个 render(template, context) 方法,将 template 中的占位符用 context 填充
-
如何使用puppet替换文件中的string
-
如何在 GitHub上删除某个 Repository 中的某个文件夹
-
linux查找目录下的所有文件中是否含有某个字符串 Linux
-
linux查找目录下的所有文件中是否含有某个字符串 Linux
-
查找目录下的所有文件中是否含有某个字符串,并且只打印出文件名
-
java字符串在内存和文件中编码的不同,如何理解二进制与编码的关系
-
使用grep -o统计文件中某个字符串出现的次数
-
如何修改json字符串中某个key对应的value值