Search code examples
posix

How can I replace all instances of a string in my entire home directory?


I am working on a library, and I made a major change. All my projects import github.com/retep-mathwizard/utils/src/..., but I have shortened my projects to github.com/retep-mathwizard/utils/.... I need to find every occurrence of it starting at ~, and replace all occurrences. Is there a way to do this?


Solution

  • sed is your friend.

    $ sed -i 's_github.com/retep-mathwizard/utils/src_github.com/retep-mathwizard/utils_g' *.txt
    

    Where *.txt is whatever text files you want to search/replace. Note that the _ is important. It's used to separate the patterns in the search-and-replace, because you have both the standard / separator and the oft-used alternative - in your pattern. The -i.bak option will tell sed to edit the files in place, and save a backup copy with the extension .bak.

    If the files are in many subdirectories, you'll need to use a combo like find and xargs.

    $ find ~ -name "*.txt" -print0 | xargs -0 sed -i.bak 's_github.com/retep-mathwizard/utils/src_github.com/retep-mathwizard/utils_g' 
    

    Again, *.txt is whatever regex will find only those files you want to replace text in.

    DISCLAIMER: As with anything involving these tools, you should try this out on something replaceable or in a new git branch first.

    EDIT: Removed extension on -i flag. As pointed out in the comments, everything is under source control, so it should be fine to do in-place editing without saving a backup file.