Here, I'd use perl
.
WORD=$word REPLACE=$replace perl -pi -e '
s/\b\Q$ENV{WORD}\E\b/$ENV{REPLACE}/g' file
sed
(even GNU sed
) has no equivalent for \Q\E
which you need here for the $word
not to be taken as a regexp. And most sed
implementations don't support -i
(or they support it with different syntax) or \b
.
\b
matches a transition between a word and non-word character.
So \b\Q1.1.2.3\E\b
would still match in 1.1.2.3.4
as .
is a non-word.
You could also do:
WORD=$word REPLACE=$replace perl -pi -e '
s/(?<!\S)\Q$ENV{WORD}\E(?!\S)/$ENV{REPLACE}/g' file
To match on $word
as long as it's not preceded nor followed by a non-spacing character. (using (?<!)
and (?!)
negative look behind/forward operators).
Note that perl
will by default work with ASCII characters. For instance, a word character would only be _a-zA-Z0-9
(\b\Q1.2.3\E\b
would match in 1.2.3é
and \S
would match individual bytes of an extended unicode spacing characters). For non-ASCII data, you'd probably want to add the -CLSD
option to perl
.
Some examples:
$ export WORD=1.1.1.3 REPLACE=REPLACE
$ printf '1.1.1.3-x 1.1.1.3\u2006 1.1.1.3.4 1.1.123 1.1.1.3\u20dd 1.1.1.3\ue9\n' > f
$ cat f
1.1.1.3-x 1.1.1.3 1.1.1.3.4 1.1.123 1.1.1.3⃝ 1.1.1.3é
$ perl -pe 's/\b\Q$ENV{WORD}\E\b/$ENV{REPLACE}/g' f
REPLACE-x REPLACE REPLACE.4 1.1.123 REPLACE⃝ REPLACEé
$ perl -CLSD -pe 's/\b\Q$ENV{WORD}\E\b/$ENV{REPLACE}/g' f
REPLACE-x REPLACE REPLACE.4 1.1.123 1.1.1.3⃝ 1.1.1.3é
$ perl -pe 's/(?<!\S)\Q$ENV{WORD}\E(?!\S)/$ENV{REPLACE}/g' f
1.1.1.3-x 1.1.1.3 1.1.1.3.4 1.1.123 1.1.1.3⃝ 1.1.1.3é
$ perl -CLSD -pe 's/(?<!\S)\Q$ENV{WORD}\E(?!\S)/$ENV{REPLACE}/g' f
1.1.1.3-x REPLACE 1.1.1.3.4 1.1.123 1.1.1.3⃝ 1.1.1.3é
$ sed "s/\b$WORD\b/$REPLACE/g" f
REPLACE-x REPLACE REPLACE.4 REPLACE REPLACE⃝ 1.1.1.3é
"{n}" = "y"
or"${n}" = "y"
? – nitishch Feb 14 '15 at 10:14\b
(word limit) to patternsed -i "s/$word\b/$replace/g"
– Costas Feb 14 '15 at 10:16s/regex/replacement/
, it's nots/string/replacement/
. For instance1.1.1.3
matches1.1.1.3
but also1.1.123
(as.
matches any character). – Stéphane Chazelas Dec 14 '15 at 12:35