[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] bash way of variable substitution
From: |
Tim Visher |
Subject: |
Re: [Help-bash] bash way of variable substitution |
Date: |
Thu, 8 Feb 2018 09:43:51 -0500 |
It's 10,000 lines of C but this is how substitution is implemented in Bash.
https://git.savannah.gnu.org/cgit/bash.git/tree/subst.c
Given the generality of your question I'm not sure what else to point you
to.
On Wed, Feb 7, 2018 at 4:15 PM, Peng Yu <address@hidden> wrote:
> Hi,
>
> I'd like to do variable substitution using the bash syntax (only allow
> things like ${x} or $x without allowing anything else in bash) instead
> of using other tools like m4. In order to not to have a conflict with
> environmental variables, I did not use bash for this implementation.
> Instead, I come up with the following implement in python. But I am
> not how variable substitution is implemented internally in bash and
> whether there are any other better and cleverer implementations.
>
> Does anybody have any other suggestions about a better implementation?
>
> $ cat varbashsub0.py
> #!/usr/bin/python
> # vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1
> fileencoding=utf-8:
>
> import sys
> import re
>
> rpl_dict = {}
>
> for s, d in zip(sys.argv[1::2], sys.argv[2::2]):
> rpl_dict[s] = d
>
> regex=r'(\\\\)|(\\\$)' +
> '|\$(([A-Za-z_][A-Za-z0-9_]*)|{([A-Za-z_][A-Za-z0-9_]*)})'
> r = re.compile(regex)
>
> def rpl_str(r, s, rpl_dict):
> result = []
> prev_end = 0
> for m in r.finditer(s):
> if m.group(1):
> varval = '\\'
> elif m.group(2):
> varval = '$'
> else:
> varname = m.group(4)
> if varname is None:
> varname = m.group(5)
>
> if varname in rpl_dict:
> varval = rpl_dict[varname]
> else:
> varval = ''
>
> result.append(s[prev_end:m.start()])
> result.append(varval)
> prev_end = m.end()
>
> result.append(s[prev_end:])
>
> return result
>
> for line in sys.stdin:
> line = line.rstrip('\n')
> print ''.join(rpl_str(r, line, rpl_dict))
>
> $ ./varbashsub0.py <<< '\\\$a'
> \$a
> $ ./varbashsub0.py <<< '\$'
> $
> $ ./varbashsub0.py <<< 'x${ab}y'
> xy
> $ ./varbashsub0.py <<< 'x$ab y'
> x y
> $ ./varbashsub0.py a 1 b 2 <<< '${a}$b'
> 12
> $ ./varbashsub0.py a 1 b 2 <<< 'x${a}${b}y'
> x12y
>
> --
> Regards,
> Peng
>
>
Re: [Help-bash] bash way of variable substitution, Pierre Gaston, 2018/02/08