I have a list of string to be replaced in files. However when I run the sed -i
(change the file directly), only the last replacement works. I think the last one override all previous changes?
#!/bin/bash
# echo "searching text to be replaced from csv file.."
mapfile -t searchArray < search
mapfile -t replacementArray < replacement
for file in *.txt;
do
echo ">>>processing $file.."
for idx in "${!searchArray[@]}"; do
echo "@@replacing ${searchArray[idx]}"
if [[ ${searchArray[idx]} != "" && ${replacementArray[idx]} != "" ]]; then
ESCAPED_REPLACE=$(printf '%s\n' "${searchArray[idx]}" | sed -e 's/[\/&]/\\&/g')
sed -i "s/$ESCAPED_REPLACE/${replacementArray[idx]}/g" "$file"
fi
done
done
Tried work on a sed file as this:
for idx in "${!searchArray[@]}"; do
if [[ ${searchArray[idx]} != "" && ${replacementArray[idx]} != "" ]];
then
ESCAPED_REPLACE=$(printf '%s\n' "${searchArray[idx]}" | sed -e
's/[\/&]/\\&/g')
printf 's/%s/%s/g\n' "$ESCAPED_REPLACE" "${replacementArray[idx]}"
fi
done >script.sed
for file in *.txt;
do
sed -f script.sed "$file" >outputfile && mv outputfile "$file"
done
But the search string has some special characters eg "${template(properties).activateDate}(pd -> \"#dateFormatCalc('$pd', 'long', 'dd MMM yyyy','-12Q')\")"
, how can I escape those special characters in *.sed
file? I mean generate that *.sed
file programmatically.
Edit: This is my search file (two rows):search string
${template(properties).activateDate}(pd -> \"#dateFormatCalc('$pd', 'long', 'dd MMM yyyy','-12Q')\")
${template(properties).activateDate}(pd -> \"#dateFormatCalc('$pd', 'long', 'dd MMM yyyy','-16')\")
This is my replacement file (two rows):
#dateCalc('dd-mm-yyyy','end','-12','Q')
#dateCalc('dd-mm-yyyy','end','-16','Q')
This is my test file (search and replace). It is a JSON file: code sample pic
{
"type": "TEXTBOX",
"type": "TEXTBOX",
"label": "${template(properties).activateDate}(pd -> \"#dateFormatCalc('$pd', 'long', 'dd MMM yyyy','-12Q')\")",
"value": "${template(properties).activateDate}(pd -> \"#dateFormatCalc('$pd', 'long', 'dd MMM yyyy','-12Q')\")",
"format": "PERCENTAGE",
"displayTotal": false,
"deactivated": false
}
Expected result should be as this:
{
"type": "TEXTBOX",
"type": "TEXTBOX",
"label": "#dateCalc('dd-mm-yyyy','end','-12','Q')",
"value": "#dateCalc('dd-mm-yyyy','end','-12','Q')",
"format": "PERCENTAGE",
"displayTotal": false,
"deactivated": false
}