Friday, June 7, 2019

Bash - Bulk file update with find and sed

Doing bulk file update (mind escapes when using complicated patterns):

#!/bin/bash

if [ -z $1 ] || [ -z $2 ]  || [ -z $3 ] || [ -z $4 ]; then
        printf "\nPlease enter:\n
        1. file command-compatible filename pattern
        2. backup suffix for affected files
        3. pattern to replace
        4. replacement\n\n
        For instance, $0 *.txt .xml-backup blue red\n
        This should replace blue with red in all txt files\n\n"
        exit
fi


filename_pattern=$1
backup_suffix=$2
pattern_to_replace=$3
replace_with=$4

find . -type f -name ${filename_pattern} -exec sed -i${backup_suffix} "s|${pattern_to_replace}|$replace_with|g" {} \+

No comments:

Post a Comment