Golang 对文件的增删改查操作
package main
import (
"bufio"
"bytes"
"fmt"
"os"
"os/exec"
"strings"
"text/template"
)
type HostsEntry struct {
IP string
Host string
}
func Add(filepath string, str []HostsEntry) error {
// 定义模板
hostsTmpl := `{{.IP}} {{.Host}}
`
// 准备数据
//hostsEntries := []HostsEntry{
// {IP: "127.0.0.1", Host: "localhost"},
// {IP: "192.168.1.100", Host: "host1.example.com"},
// {IP: "192.168.1.101", Host: "host2.example.com"},
//}
hostsEntries := str
// 打开文件
file, err := os.OpenFile(filepath, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer file.Close()
// 创建模板
tmpl, err := template.New("host").Parse(hostsTmpl)
if err != nil {
return err
}
// 应用模板并追加到文件
for _, entry := range hostsEntries {
err = tmpl.Execute(file, entry)
if err != nil {
return err
}
}
return nil
}
func Delete(filepath string, str string) error {
file, err := os.OpenFile(filepath, os.O_RDWR, 0644)
if err != nil {
return err
}
defer file.Close()
// 创建一个新的临时文件
tmpFile, err := os.CreateTemp("", "tempfile")
if err != nil {
return err
}
defer tmpFile.Close()
// 扫描文件并删除包含指定字符串的行
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if !strings.Contains(line, str) {
_, err := tmpFile.WriteString(line + "\n")
if err != nil {
return err
}
}
}
// 关闭文件并重命名临时文件
file.Close()
tmpFile.Close()
err = os.Rename(tmpFile.Name(), filepath)
if err != nil {
return err
}
return nil
}
func Modify(filepath, oldstr, newstr string) error {
// 打开文件
file, err := os.OpenFile(filepath, os.O_RDWR, 0644)
if err != nil {
return err
}
defer file.Close()
// 读取文件并存储在内存中
scanner := bufio.NewScanner(file)
var lines []string
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
// 修改所需的行
for i, line := range lines {
if strings.Contains(line, oldstr) {
lines[i] = newstr
break
}
}
// 将修改后的数据写回文件中
file.Truncate(0) // 清空文件内容
file.Seek(0, 0) // 将文件指针移到文件开头
writer := bufio.NewWriter(file)
for _, line := range lines {
fmt.Fprintln(writer, line)
}
writer.Flush()
return nil
}
func Get(filepath, str string) (bool, error) {
// 打开文件
file, err := os.OpenFile(filepath, os.O_RDONLY, 0644)
if err != nil {
return true, err
}
defer file.Close()
// 扫描文件并删除包含指定字符串的行
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if !strings.Contains(line, str) {
return true, nil
}
}
return false, nil
}
func Shellout(command string) (error, string, string) {
const ShellToUse = `bash`
var stdout bytes.Buffer
var stderr bytes.Buffer
cmd := exec.Command(ShellToUse, "-c", command)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
return err, stdout.String(), stderr.String()
}
func main() {
hostsEntries := []HostsEntry{
{IP: "127.0.0.1", Host: "localhost"},
{IP: "192.168.1.100", Host: "host1.example.com"},
{IP: "192.168.1.101", Host: "host2.example.com"},
}
Add("drop.conf", hostsEntries)
result, err := Get("drop.conf", "192.168.1.100")
if err != nil {
fmt.Println(err)
}
fmt.Println(result)
Modify("drop.conf", "host1.example.com", "1.1.1.1 host111.example.com")
Delete("drop.conf", "host111.example.com")
err, stdout, stderr := Shellout("ls -al")
if err != nil {
fmt.Println("执行错误")
}
fmt.Println(stdout, stderr)
}
本文作者:dqforgive-sudo
本文链接:https://www.cnblogs.com/dqforgive-sudo/p/17238522.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步