help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] Variables in substitution replacements


From: Davide Brini
Subject: Re: [Help-bash] Variables in substitution replacements
Date: Wed, 10 Aug 2016 13:13:36 +0200

On Wed, 10 Aug 2016 00:29:06 -0400, Eli Barzilay <address@hidden> wrote:

> The following seems like a weird behavior, given the context I doubt
> that it's a bug but it seems good to confirm, just in case.
> 
> I'm trying to replace a character given via a variable by something
> else, and I thought that this should do it:
> 
>     "${str//$r/<>}"
> 
> but it looks like this doesn't work, since ... the contents of $r is
> partially re-interpreted as a pattern??  That's the only explanation I
> have for...
> 
>     $ t() { echo "${2//$1/<>}"; }
>     $ t '\' 'foo\*bar'   # ...this not doing anything
>     foo\*bar
>     $ t '*' 'foo\*bar'   # ...and this replacing everything
>     <>

You should use quotes to prevent expansion, so I think you want this:

$ t() { echo "${2//"$1"/<>}"; }
$ t '*' 'foo\*bar'
foo\<>bar

> but if it *is* re-interpreted as a pattern then I don't see how this
> happens:
> 
>     $ t '"*"' 'foo\*bar'
>     foo\*bar

There's no match for "*" (as a pattern, but not even if it were
taken literally) in foo\*bar, so no replacement happens.

> since I'd expect the quoted quotes to be part of that pattern; and there
> are also these:
> 
>     $ t '"*"' '"foo\*bar"'
>     <>

Now "*" (as a pattern) matches the whole input, which does have quotes, so
the whole thing is replaced by <>.

>     $ t '"*"' 'f"oo\*ba"r'
>     f<>r

Here the pattern "*" matches "oo\*ba" in the input, so that part is
replaced with <>.

-- 
D.



reply via email to

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