If you are able to run a script, here is what I did for a similar situation:
Using a dictionary/hashMap (associative array) and variables for the sed
command, we can loop through the array to replace several strings. Including a wildcard in the name_pattern
will allow to replace in-place in files with a pattern (this could be something like name_pattern='File*.txt'
) in a specific directory (source_dir
).
All the changes are written in the logfile
in the destin_dir
#!/bin/bash
source_dir=source_path
destin_dir=destin_path
logfile='sedOutput.txt'
name_pattern='File.txt'
echo "--Begin $(date)--" | tee -a $destin_dir/$logfile
echo "Source_DIR=$source_dir destin_DIR=$destin_dir "
declare -A pairs=(
['WHAT1']='FOR1'
['OTHER_string_to replace']='string replaced'
)
for i in "${!pairs[@]}"; do
j=${pairs[$i]}
echo "[$i]=$j"
replace_what=$i
replace_for=$j
echo " "
echo "Replace: $replace_what for: $replace_for"
find $source_dir -name $name_pattern | xargs sed -i "s/$replace_what/$replace_for/g"
find $source_dir -name $name_pattern | xargs -I{} grep -n "$replace_for" {} /dev/null | tee -a $destin_dir/$logfile
done
echo " "
echo "----End $(date)---" | tee -a $destin_dir/$logfile
First, the pairs array is declared, each pair is a replacement string, then WHAT1
will be replaced for FOR1
and OTHER_string_to replace
will be replaced for string replaced
in the file File.txt
. In the loop the array is read, the first member of the pair is retrieved as replace_what=$i
and the second as replace_for=$j
. The find
command searches in the directory the filename (that may contain a wildcard) and the sed -i
command replaces in the same file(s) what was previously defined. Finally I added a grep
redirected to the logfile to log the changes made in the file(s).
This worked for me in GNU Bash 4.3
sed 4.2.2
and based upon VasyaNovikov's answer for Loop over tuples in bash.
sed -i 's/abc/xyz/g' xa*
? – Paul R