内容替换
ReplaceFile
func ReplaceFile(search, replace, path string) error
func ExampleReplaceFile() {
// init
var (
fileName = "gflie_example.txt"
tempDir = gfile.TempDir("gfile_example_replace")
tempFile = gfile.Join(tempDir, fileName)
)
// write contents
gfile.PutContents(tempFile, "goframe example content")
// read contents
fmt.Println(gfile.GetContents(tempFile))
// It replaces content directly by file path.
gfile.ReplaceFile("content", "replace word", tempFile)
fmt.Println(gfile.GetContents(tempFile))
// Output:
// goframe example content
// goframe example replace word
}
ReplaceFileFunc
func ReplaceFileFunc(f func(path, content string) string, path string) error
func ExampleReplaceFileFunc() {
// init
var (
fileName = "gflie_example.txt"
tempDir = gfile.TempDir("gfile_example_replace")
tempFile = gfile.Join(tempDir, fileName)
)
// write contents
gfile.PutContents(tempFile, "goframe example 123")
// read contents
fmt.Println(gfile.GetContents(tempFile))
// It replaces content directly by file path and callback function.
gfile.ReplaceFileFunc(func(path, content string) string {
// Replace with regular match
reg, _ := regexp.Compile(`\d{3}`)
return reg.ReplaceAllString(content, "[num]")
}, tempFile)
fmt.Println(gfile.GetContents(tempFile))
// Output:
// goframe example 123
// goframe example [num]
}
ReplaceDir
- 说明:扫描指定目录,替换符合条件的文件的指定内容为新内容
- 格式:
func ReplaceDir(search, replace, path, pattern string, recursive ...bool) error
func ExampleReplaceDir() {
// init
var (
fileName = "gflie_example.txt"
tempDir = gfile.TempDir("gfile_example_replace")
tempFile = gfile.Join(tempDir, fileName)
)
// write contents
gfile.PutContents(tempFile, "goframe example content")
// read contents
fmt.Println(gfile.GetContents(tempFile))
// It replaces content of all files under specified directory recursively.
gfile.ReplaceDir("content", "replace word", tempDir, "gflie_example.txt", true)
// read contents
fmt.Println(gfile.GetContents(tempFile))
// Output:
// goframe example content
// goframe example replace word
}
ReplaceDirFunc
- 说明:扫描指定目录,使用自定义函数替换符合条件的文件的指定内容为新内容
- 格式:
func ReplaceDirFunc(f func(path, content string) string, path, pattern string, recursive ...bool) error
func ExampleReplaceDirFunc() {
// init
var (
fileName = "gflie_example.txt"
tempDir = gfile.TempDir("gfile_example_replace")
tempFile = gfile.Join(tempDir, fileName)
)
// write contents
gfile.PutContents(tempFile, "goframe example 123")
// read contents
fmt.Println(gfile.GetContents(tempFile))
// It replaces content of all files under specified directory with custom callback function recursively.
gfile.ReplaceDirFunc(func(path, content string) string {
// Replace with regular match
reg, _ := regexp.Compile(`\d{3}`)
return reg.ReplaceAllString(content, "[num]")
}, tempDir, "gflie_example.txt", true)
fmt.Println(gfile.GetContents(tempFile))
// Output:
// goframe example 123
// goframe example [num]
}