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

Re: sed question



On 2019-12-06 at 14:40, songbird wrote:

> Greg Wooledge wrote: ...
>> Ideally, you'd just stop trying to use sed with user-supplied
>> variables injected into the code.  Sed was never built to be safe
>> for that kind of work.
> 
> sed was designed to operate on streams.  a sequence of characters is
> a stream.  i don't see any reason why putting the variable into the
> middle of that expression means anything different.

Because sed doesn't see the variable; the variable is handled by the
shell. sed only sees the result of expanding the variable.

If the variable doesn't contain the delimiting token (the character
after the initial 's' - in this case, '/'), then things work out fine.

But if the variable does contain that token, then what sed sees contains
too many instances of that token, and the result is invalid sed syntax -
so sed errors out, because it doesn't know what to do with what it saw.


For example, 's/hello/newstring/' would be a valid sed 's'-expression,
but 's/a/b/newstring/' would not; the former contains three instances of
the delimiting token, which is valid, but the former contains four,
which is not.

If you have the sed expression 's/${oldstring}/newstring/', and you
define oldstring as having the value 'hello' then sed sees the first
expression, and you get the good result.

But if you instead define oldstring as having the value 'a/b', then sed
sees the second expression, and you get a syntax error.


(Assuming I'm not mixing things up right now, anyway.)

-- 
   The Wanderer

The reasonable man adapts himself to the world; the unreasonable one
persists in trying to adapt the world to himself. Therefore all
progress depends on the unreasonable man.         -- George Bernard Shaw

Attachment: signature.asc
Description: OpenPGP digital signature


Reply to: