1

I wish to sed some strings part of an XML .SLA scribus file, in a script.

Simplified script :

replaced="$1"
replacement="$2"
sed -i "s/$replaced/$replacement/gI" afile.sla

Issue is that $1 and $2 have to be escaped beforehand. For example with $2 being an empty string, this works fine : sed -i "s/<ITEXT FONT=\"LiberationSerif\" FCOLOR=\"Green\" CH=\"Youpeeee\"\/>//gI" afile.sla

This works fine and this is the goal to achieve, but the $1 and $2 are not escaped at first. I have found several questions and answers (as How can I escape a double quote inside double quotes?) on how the escaped strings should be, but none on how a script can do this escaping. Both the / and the " should be escaped.

So which script command will escape the $1 and $2 strings so as to use them as argument to sed ?

JLuc
  • 333
  • 5
  • 15
  • Thanks @Wiktor... but that's frightening. If *this* is the answer, then bash is not the tool to do that because it's too esoteric. I'd rather write a C or php tool or whatever to do the whole job :-/ – JLuc Jan 31 '22 at 11:28
  • Sure, I'd use Python for this. And since you want to manipulate XML, I'd use a library to work with this syntax. Regex is not the best tool to work with mark-up languages. – Wiktor Stribiżew Jan 31 '22 at 11:32
  • Well, as for now this script has a general purpose and it could be used to replace any part in that xml : strings, elements, attributes values... or a mix of such parts. I found that other question https://stackoverflow.com/questions/26009514/escaping-double-quotes-in-a-variable-in-a-shell-script So, how about simply `sed 's/["/]/\\&/g'` ? – JLuc Jan 31 '22 at 11:38
  • This seems to do the job ``` escapedsearch=$(LC_ALL=C sed 's/["/]/\\&/g' <<<"$xmlsearched") escapedreplace=$(LC_ALL=C sed 's/["/]/\\&/g' <<<"$replaced") sed -i "s/$escapedsearch/$escapedreplace/gI" "$fic.sla" ``` – JLuc Jan 31 '22 at 11:53

1 Answers1

0

I guess a double sed probably could solve this, making sure all characters are escaped prior to replacing.

_escapes() { sed 's/[^^\\]/[&]/g; s/\^/\\^/g; s/\\/\\\\/g' <<<$1 ;}
replaced=$(_escapes "$1")
replacement=$(_escapes "$2")
sed -i "s/$replaced/$replacement/gI" afile.sla
Kaffe Myers
  • 424
  • 3
  • 9