How to change all occurrences of a word in all files in a directory

后端 未结 4 1823
感动是毒
感动是毒 2020-12-13 02:52

I was in the process of creating a User class where one of the methods was get_privileges();.

After hours of slamming my head into the keyb

4条回答
  •  天涯浪人
    2020-12-13 03:10

    I generally use this short script, which will rename a string in all files and all directory names and filenames. To use it, you can copy the text below into a file called replace_string, run sudo chmod u+x replace_string and then move it into your sudo mv replace_string /usr/local/bin folder to be able to execute it in any directory.

    NOTE: this only works on linux (tested on ubuntu), and fails on MacOS. Also be careful with this because it can mess up things like git files. I haven't tested it on binaries either.

    #!/usr/bin/env bash
    
    # This will replace all instances of a string in folder names, filenames,
    # and within files.  Sometimes you have to run it twice, if directory names change.
    
    
    # Example usage:
    # replace_string apple banana
    
    echo $1
    echo $2
    
    find ./ -type f -exec sed -i -e "s/$1/$2/g" {} \;  # rename within files
    find ./ -type d -exec rename "s/$1/$2/g" {} \;    # rename directories
    find ./ -type f -exec rename "s/$1/$2/g" {} \;  # rename files
    

提交回复
热议问题