help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: sed with Variable Substitution in the command


From: Steve Matzura
Subject: Re: sed with Variable Substitution in the command
Date: Thu, 19 Sep 2024 14:29:59 -0400
User-agent: Mozilla Thunderbird Beta

Thanks for this. I never think about perl. Something else new to learn.


On 9/19/2024 10:23 AM, Greg Wooledge wrote:
On Thu, Sep 19, 2024 at 10:03:01 -0400, Steve Matzura wrote:
sed -i 's/replace-this/$with_this_variable/'
The simplistic answer is "you want double quotes instead of single quotes".

     sed -i "s/replace-this/$with_this_variable/"

However, the problem goes a bit deeper than that.  Sed *always* uses
regular expressions to match things.  There is no option to use a
plain string.  Therefore, if your replace-this has any special characters
in it (or has the *possibility* of it, e.g. if it's a variable as well),
then you may get unpredictable results.

(Slashes or newlines in the $with_this_variable content would also cause
an issue.)

<https://mywiki.wooledge.org/BashFAQ/021> suggests using perl instead:

     in="$search" out="$replace" perl -pi -e 's/\Q$ENV{"in"}/$ENV{"out"}/g' ./*

This forces a plain string match for the "in" side, so it'll work no
matter what characters are used.

There are other examples given on that page as well.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]