Skip to content

bash function to search and replace in all files with special extension recursively

Pretty much, the code is below. It is a part of my function collection for the bash.

####
# Replaces a string in all files in given path and below
# taken from: http://www.cyberciti.biz/faq/unix-linux-replace-string-words-in-many-files/
# taken from: http://stackoverflow.com/questions/4437901/find-and-replace-string-in-a-file
# taken from: http://stackoverflow.com/questions/7450324/how-do-i-replace-a-string-with-another-string-in-all-files-below-my-current-dir
#
# @author stev leibelt 
# @since 2013-7-30
####
function net_bazzline_replace_string_in_files ()
{
    if [[ $# -lt 3 ]]; then
        echo 'invalid number of arguments provided'
        echo 'command search replace fileextension [path]'
        return 1
    fi

    if [[ $# -eq 4 ]]; then
        find "$4" -name "*.$3" -type f -exec sed -i 's/'"$1"'/'"$2"'/g' {} \;
    else
        find . -name "*.$3" -type f -exec sed -i 's/'"$1"'/'"$2"'/g' {} \;
    fi
}

php - how to explode a string with multiple delimiters without using preg_split

The task is to split a string by a set of delimiters. preg_split could be an option but there is an easier way ;-). Why not combine str_replace and explode? First, we replace all known delimiters with a special (and hopefully unique) string. After that, we have a string with one delimiter, so it became a suitable task for explode. Take a look to the sourcecode below.

<\?php $nl = PHP_EOL; $string = 'Word1, Word2 , Word3 and Word4 or Word5 oder Wort6 / Word 7 Word-8'; $delimiters = array( ', ', ' , ', ' oder ', ' or ', ' / ', ' und ', ' and ' ); $words = array(); $unionPlaceholder = 'ARTODETO_BAZZLINE_NET_UNION_PLACEHOLDER'; $unifiedString = str_replace($delimiters, $unionPlaceholder, $string); $words = explode($unionPlaceholder, $unifiedString); echo 'splitting following string:' . $nl . '"' . $string . '"' . $nl; echo '----' . $nl; foreach ($words as $word) { echo $word . $nl; }
You see, no magic but a possible timesaver. Have fun with it.