用golang如何替换某个文件中的字符串


Posted in Golang onApril 25, 2021

用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如何替换某个文件中的字符串

将空格替换为逗号:

用golang如何替换某个文件中的字符串

新文件:

用golang如何替换某个文件中的字符串

补充: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方法。

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

Golang 相关文章推荐
go语言map与string的相互转换的实现
Apr 07 Golang
golang import自定义包方式
Apr 29 Golang
golang 在windows中设置环境变量的操作
Apr 29 Golang
解决go在函数退出后子协程的退出问题
Apr 30 Golang
Golang Gob编码(gob包的使用详解)
May 07 Golang
关于golang高并发的实现与注意事项说明
May 08 Golang
go web 预防跨站脚本的实现方式
Jun 11 Golang
手把手教你导入Go语言第三方库
Aug 04 Golang
一文搞懂Golang 时间和日期相关函数
Dec 06 Golang
Go语言实现一个简单的并发聊天室的项目实战
Mar 18 Golang
Go语言特点及基本数据类型使用详解
Mar 21 Golang
Golang使用Panic与Recover进行错误捕获
Mar 22 Golang
Golang 正则匹配效率详解
golang正则之命名分组方式
Apr 25 #Golang
go语言-在mac下brew升级golang
Apr 25 #Golang
go原生库的中bytes.Buffer用法
Apr 25 #Golang
Go缓冲channel和非缓冲channel的区别说明
Apr 25 #Golang
Go语言使用select{}阻塞main函数介绍
win10下go mod配置方式
You might like
Javascript与PHP验证用户输入URL地址是否正确
2014/10/09 PHP
Yii2 hasOne(), hasMany() 实现三表关联的方法(两种)
2017/02/15 PHP
javascript 客户端验证上传图片的大小(兼容IE和火狐)
2009/08/15 Javascript
jQuery中change事件用法实例
2014/12/26 Javascript
javascript鼠标滑过显示二级菜单特效
2020/11/18 Javascript
jQuery中常用动画效果函数(日常整理)
2016/09/17 Javascript
AngularJS基于ui-route实现深层路由的方法【路由嵌套】
2016/12/14 Javascript
深入理解Javascript中的观察者模式
2017/02/20 Javascript
详解vue slot插槽的使用方法
2017/06/13 Javascript
JavaScript中使用参数个数实现重载功能
2017/09/01 Javascript
浅谈vue-router2路由参数注意的问题
2017/11/08 Javascript
Node实战之不同环境下配置文件使用教程
2018/01/02 Javascript
Vue.js实现数据响应的方法
2018/08/13 Javascript
Vuex中的State使用介绍
2019/01/19 Javascript
解决vue中使用proxy配置不同端口和ip接口问题
2019/08/14 Javascript
微信小程序可滑动周日历组件使用详解
2019/10/21 Javascript
JavaScript实现捕获鼠标坐标
2020/04/12 Javascript
jQuery zTree如何改变指定节点文本样式
2020/10/16 jQuery
Python常用模块用法分析
2014/09/08 Python
Python使用爬虫猜密码
2016/02/19 Python
Python字典,函数,全局变量代码解析
2017/12/18 Python
聊聊python里如何用Borg pattern实现的单例模式
2019/06/06 Python
Python实现新型冠状病毒传播模型及预测代码实例
2020/02/05 Python
解决Python paramiko 模块远程执行ssh 命令 nohup 不生效的问题
2020/07/14 Python
Python爬虫破解登陆哔哩哔哩的方法
2020/11/17 Python
使用pandas实现筛选出指定列值所对应的行
2020/12/13 Python
python 获取谷歌浏览器保存的密码
2021/01/06 Python
日本化妆品植村秀俄罗斯官方网站:Shu Uemura俄罗斯
2020/02/01 全球购物
人事助理岗位职责
2013/11/18 职场文书
学生打架检讨书
2014/02/14 职场文书
化妆品活动策划方案
2014/05/23 职场文书
党的群众路线教育实践活动对照检查材料(四风)
2014/09/27 职场文书
离婚财产处理协议书
2014/09/30 职场文书
党小组推荐意见
2015/06/02 职场文书
三好学生竞选稿
2015/11/21 职场文书
《吸血鬼幸存者》新内容发布 追加多个全新模式
2022/04/07 其他游戏