Существует ли более простой портабельный (POSIX-совместимый) способ заменить в строке подстроку, чем этот?
plain_subst() {
local s="$1"
local p_r='s/[.*[^$]/\\&/g'
local p="`printf "%s\n" "$2" | sed "$p_r"`"
local r_r='s/[&\\\/]/\\&/g'
local r="`printf "%s\n" "$3" | sed "$r_r"`"
printf "%s\n" "$s" | sed "s/$p/$r/g"
}
Тестовый набор:
plain_subst 'The quick brown fox jumps over the lazy dog.' 'fox' 'cat'
plain_subst 'The quick brown fox jumps over the lazy dog.' 'fox' 'cat&'
plain_subst 'The quick brown fox jumps over the lazy dog.' 'fox' 'cat\1'
plain_subst 'The quick brown fox jumps over the lazy dog.' 'fox' 'cat/'
plain_subst 'The quick brown fox jumps over the lazy dog.' '.' '!'
plain_subst ',.,' '.' '!'
plain_subst ',.*,' '.*' '!'
plain_subst ',[.],' '[.]' '!'
plain_subst ',^,' '^' '!'
plain_subst ',$,' '$' '!'
The quick brown cat jumps over the lazy dog.
The quick brown cat& jumps over the lazy dog.
The quick brown cat\1 jumps over the lazy dog.
The quick brown cat/ jumps over the lazy dog.
The quick brown fox jumps over the lazy dog!
,!,
,!,
,!,
,!,
,!,