How to grep and replace

后端 未结 9 1583
囚心锁ツ
囚心锁ツ 2020-11-27 08:47

I need to recursively search for a specified string within all files and subdirectories within a directory and replace this string with another string.

I know that t

9条回答
  •  一生所求
    2020-11-27 09:24

    Be very careful when using find and sed in a git repo! If you don't exclude the binary files you can end up with this error:

    error: bad index file sha1 signature 
    fatal: index file corrupt
    

    To solve this error you need to revert the sed by replacing your new_string with your old_string. This will revert your replaced strings, so you will be back to the beginning of the problem.

    The correct way to search for a string and replace it is to skip find and use grep instead in order to ignore the binary files:

    sed -ri -e "s/old_string/new_string/g" $(grep -Elr --binary-files=without-match "old_string" "/files_dir")
    

    Credits for @hobs

提交回复
热议问题