31 lines
785 B
Go
31 lines
785 B
Go
package config
|
||
|
||
import (
|
||
"fmt"
|
||
"os"
|
||
"regexp"
|
||
)
|
||
|
||
// SedReplace 替换文件内容,文件来自外部文件配置config传入
|
||
//
|
||
// sed 's/port: [0-9]\+ # trace port/port: 6964 # trace port/' /usr/local/etc/omc/omc.yaml
|
||
func SedReplace(pattern, replacement string) error {
|
||
// 外部文件配置
|
||
externalConfig := conf.GetString("config")
|
||
if externalConfig == "" {
|
||
return fmt.Errorf("config file path not found")
|
||
}
|
||
// 读取文件内容
|
||
data, err := os.ReadFile(externalConfig)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
|
||
// 定义正则表达式
|
||
re := regexp.MustCompile(pattern)
|
||
// 使用正则替换,将匹配到的部分替换为新的内容
|
||
replacedData := re.ReplaceAll(data, []byte(replacement))
|
||
// 写回文件
|
||
return os.WriteFile(externalConfig, replacedData, 0644)
|
||
}
|