Best way to do a find/replace in several files?

后端 未结 5 544
北恋
北恋 2021-01-30 01:56

what\'s the best way to do this? I\'m no command line warrior, but I was thinking there\'s possibly a way of using grep and cat.

I just want to

5条回答
  •  别那么骄傲
    2021-01-30 02:16

    I'll throw in another example for folks using ag, The Silver Searcher to do find/replace operations on multiple files.

    Complete example:

    ag -l "search string" | xargs sed -i '' -e 's/from/to/g'
    

    If we break this down, what we get is:

    # returns a list of files containing matching string
    ag -l "search string"
    

    Next, we have:

    # consume the list of piped files and prepare to run foregoing command
    # for each file delimited by newline
    xargs
    

    Finally, the string replacement command:

    # -i '' means edit files in place and the '' means do not create a backup
    # -e 's/from/to/g' specifies the command to run, in this case,
    # global, search and replace
    
    sed -i '' -e 's/from/to/g'
    

提交回复
热议问题