Replace specified string in Go language (for multiple text files)

Asked 2 years ago, Updated 2 years ago, 464 views

I created a program to replace the text file (recursively search) under the specified directory in Go language with the specified string, but I entered the string (before, after)
If you know how to make available to the function visit, please let me know.

newContents: = bytes.Replace(read, before, after, -1)

I'd like to use it, but I don't know how to make it work.

package main

import(
    "Bufio".
    "bytes"
    "fmt"
    "io/ioutil"
    "os"
    "path/filepath"
)

func visit(path string, fios.FileInfo, error) error {

    if err!=nil{
        return err
    }

    if!!fi.IsDir(){
        return nil //
    }

    matched, err: = filepath.Match("*.txt", fi.Name())

    if err!=nil{
        panic(err)
    }

    if matched {
        read,err: =ioutil.ReadFile(path)
        if err!=nil{
            panic(err)
        }
        fmt.Println(path)
        newContents: = bytes.Replace(read, before, after, -1)
        err=ioutil.WriteFile(path, newContents, os.ModePerm)
        if err!=nil{
            panic(err)
        }

    }

    return nil
}

funcmain(){
    root: = input ("file path")
    before: = input ("pre-replacement string")
    after: = input ("replaced string")
    err —=filepath.Walk (root, visit)
    if err!=nil{
        panic(err)
    }
}

func input(msg string) string {
    scanner:=bufio.NewScanner(os.Stdin)
    fmt.Print(msg+":")
    scanner.Scan()
    return scanner.Text()
}

go

2022-09-30 21:55

1 Answers

How do I make the string you entered (before, after) available to the function visit

?

Here's how to use closure.

package main

import(
    "Bufio".
    "bytes"
    "fmt"
    "io/ioutil"
    "os"
    "path/filepath"
)

func input(msg string) string {
    scanner:=bufio.NewScanner(os.Stdin)
    fmt.Print(msg+":")
    scanner.Scan()
    return scanner.Text()
}

US>func replaceFileContents(path string, before, after[]byte) error {
    read,err: =ioutil.ReadFile(path)
    if err!=nil{
        return err
    }

    fmt.Println(path)
    if bytes.Contains(read, before) {
        newContents: = bytes.Replace(read, before, after, -1)
        err=ioutil.WriteFile(path, newContents, os.ModePerm)
        if err!=nil{
            return err
        }
    }

    return nil
}

funcmain(){
    root: = input ("file path")
    before: = [ ] byte (input("pre-replacement string")
    after: = [ ] byte (input("replaceable string")

    error: = filepath.Walk(root, func(path string, fios.FileInfo, error) error {
        if err!=nil{
            return err
        }

        if fi.IsDir()||filepath.Ext(fi.Name())!=".txt"{
            return nil
        }

        return replaceFileContents (path, before, after)
    })

    if err!=nil{
        panic(err)
    }
}


2022-09-30 21:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.