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

后端 未结 4 1810
感动是毒
感动是毒 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:00

    A variation that takes into account subdirectories (untested):

    find /var/www -type f -exec sed -i 's/privelages/privileges/g' {} \;
    

    This will find all files (not directories, specified by -type f) under /var/www, and perform a sed command to replace "privelages" with "privileges" on each file it finds.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-13 03:15

    for Mac OS:

    find . -type f -name '*.sql' -exec sed -i '' s/privelages/privileges/ {} +
    

    Matwilso's script from above would then look like this if it were designed to work on Mac OS

    #!/bin/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 -name '*.sql' -exec sed -i '' s/${1}/${2}/ {} + # inside sql scripts
    
    0 讨论(0)
  • 2020-12-13 03:16

    Check this out: http://www.cyberciti.biz/faq/unix-linux-replace-string-words-in-many-files/

    cd /var/www
    sed -i 's/privelages/privileges/g' *
    
    0 讨论(0)
提交回复
热议问题