dongza3124
dongza3124
2017-07-06 00:38

用文件中的模式替换字符串

  • sed
已采纳

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dpsfay2510 dpsfay2510 4年前

    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
    ", 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
    ", speed)
    }
    
    点赞 评论 复制链接分享
  • dqfr90979 dqfr90979 4年前

    Do

    gofmt -w -r "printf -> println" .
    

    Note that make backup file before do this.

    点赞 评论 复制链接分享