Re: sed: How to avoid making changes within a literal string?
Dave S. wrote:
> As I mentioned in another posting, I am writing a rudimentary
> Pascal-to-C++ translator using a hodgepodge of sed scripts and C
> programs. One of the few important remaining tasks is to change one of
> my sed scripts so that it will not do what it does now, which is to
> recklessly replace all occurrences of "and", "or", and "not" with "&&",
> "||", and "!".
>
> The translator does need to make those conversions, but only if the
> word "and", "or", or "not" is not part of a literal string.
>
> Example:
> This:
> if not ( ( a and b ) or ( c and d ) )
> Should become:
> if ( ! ( ( a && b ) || ( c && d )) )
>
> However, this:
> write(output) << "Send receipt and sample of blood to rebateshq.com
> and expect not to get a reply." << NL;
> Should NOT become this:
> write(output) << "Send receipt && sample of blood to rebateshq.com
> && expect ! to get a reply." << NL;
This is where Perl Compatible Regex rocks, here is a simple example of
how to change 'and' to &&, others are similar..
perl -0777pe 's/("[^"]*")|and/ $1 or "&&" /eg' file.txt
more robust forms may include escaped quotes, but may looks a little
more noisy..
Xicheng
|