I'm developing a POSIX compliant script in which I want to do a dynamic replace of strings, something like:
sed "s/${pattern}/${replace}/g"
Problem: if the pattern includes the delimiting character, sed returns error, and I want to be able to use all possible characters.
Attempt (with regex): using a non printable delimiter character:
( Edited to correct syntax)
d=$(printf '\1') sed "s${d}${pattern}${d}${replace}${d}g"Probably not portable.
Attempt (with regex): if pattern contains a certain delimiter, uses another delimiter
(edited: now in POSIX-WAY):
test "${pattern#*$delim}" != "${pattern}" && delim='@' sed "s${delim}${pattern}${delim}${replace}${delim}g"Not bad but if the pattern contain both / more @ sed would return error.
Edited Solution (without regex): Following this, escaping chars related to regular expressions.
pattern=$(printf '%s\n' "${pattern}" | sed 's:[][\/.^$*]:\\&:g') replace=$(printf '%s\n' "${replace}" | sed 's:[\/&]:\\&:g;$!s/$/\\/')
Is there a better POSIX compliant solution with or without sed?