gosedgolint

replace string with patterns in file


I've used sed to replace variables on *.go files using sed -i 's/\<old_name\>/newName/g' *.go My objective is to eliminate golinter errors. How can strings with common patterns, e.g. replace 1 with 2

  1. fmt.Printf("blah blah blah") or fmt.Printf("yadda yadda yadda")
  2. fmt.Println("blah blah blah") or fmt.Println("yadda yadda yadda")

In this case, we do NOT want to replace: 1. fmt.Printf("print speed= %d",speed) //So the key here is the ending pattern should be "). 2. log.Printf statements //only replace "fmt." Any pointers on this?


Solution

  • I'm slightly confused by your question, but think you're trying to do the following:

    replace      printf("yada yada yada") with println("yada yada yada")
    not replace  printf("print speed = %d", speed)
    

    If that is the case, I would do something like the following:

    sed -i '/Printf(\".*\")/ s/Printf/Println/g' *.go
    

    That should leave cases intact where you actually want to use formatting. Here is an example:

    [sborza@msandn]:~$ cat tester.go
    package main
    
    import "fmt"
    
    func main() {
            speed = 1
            fmt.Printf("vim-go")
            fmt.Printf("speed = %d\n", speed)
    }
    
    [sborza@msandn]:~$ sed '/Printf(\".*\")/ s/Printf/Println/g' tester.go
    package main
    
    import "fmt"
    
    func main() {
            speed = 1
            fmt.Println("vim-go")
            fmt.Printf("speed = %d\n", speed)
    }