考虑到您对ioutil.WriteFile()
的调用与"通过示例编写文件"中使用的内容一致,这应该可以工作。
但是,在Go by example文章中,它在写入调用后立即检查了err。
您在测试范围之外检查了err:
if matched {
read, err := ioutil.ReadFile(path)
fmt.Println(" This is the name of the file", fi.Name())
if strings.Contains(string(read), sam) {
fmt.Println("this file contain that word")
Value := strings.ToUpper(sam)
fmt.Println(Value)
err = ioutil.WriteFile(fi.Name(), []byte(Value), 0644)
} else {
fmt.Println(" the word is not in the file")
}
check(err) <===== too late
}
你正在测试的错误是在读取文件时 (ioutil.ReadFile
) 产生的,这是由于区块和作用域引起的。
你需要在写入调用后立即检查错误。
err = ioutil.WriteFile(fi.Name(), []byte(Value), 0644)
check(err) <===== too late
由于 WriteFile 会覆盖整个文件,你可以使用 strings.Replace() 将单词替换为其大写形式:
r := string(read)
r = strings.Replace(r, sam, strings.ToUpper(sam), -1)
err := ioutil.WriteFile(fi.Name(), []byte(r), 0644)
为了进行不区分大小写的替换,请像在"
如何在Go中使用不区分大小写的正则表达式?"中那样使用正则表达式。然后,使用
func (*Regexp) ReplaceAllString
:
re := regexp.MustCompile("(?i)\\b"+sam+"\\b")
r = re.ReplaceAllString(r, strings.ToUpper(sam))
err := ioutil.WriteFile(fi.Name(), []byte(r), 0644)
请注意
\b
:使用
单词边界来查找任何以
sam
内容开头和结尾的
单词(而不是查找包含
sam
内容的子字符串)
如果您想替换子字符串,只需省略
\b
:
re := regexp.MustCompile("(?i)"+sam)
err
的值吗?我认为这会告诉你出了什么问题... - juliencerr
是否为nil
或者是否有其他值。如果有的话,那么这个值是什么。 - julienc