[ale] sed/awk/perl whatever question

fletch at phydeaux.org fletch at phydeaux.org
Wed Nov 4 10:11:43 EST 2009


[...]
> One interesting thing about this problem is that the strings in file1
> are not regular expressions and shouldn't be treated as such, but
> the easiest ways to solve this problem in sed/awk/perl involve using
> them as regular expressions.  If they're really strings like "xyz123",
> then that's not a problem, but if they're allowed to be more general,
> they could contain characters that have meaning to the regular
> expression parser.
>
> For example, if "a[b]c" is in file1 and you want to replace "a[b]c",
> square brackets and all, in file2 with "XXXX", then it won't work.
> And it will replace "abc" mistakenly.

This is why Perl has quotemeta[1] and the "\Qblah\E" escapes in double
quoted strings (both of which automagically backwhack anything that might
be interpreted in a "special" way (passed through a shell, used as a
regexp, yadda yadda).  You can obviously do the same elsewhere; e.g., in
Ruby you could extend String

class String
  def quotemeta
    dup.quotemeta!
  end
  def quotemeta!
    gsub!( %r/([^A-Za-z_0-9])/ ) { |x| "\\#{x}" }
  end
end

[1] http://perldoc.perl.org/functions/quotemeta.html

-- 
Fletch                | "If you find my answers frightening,       __`'/|
fletch at phydeaux.org|  Vincent, you should cease askin'          \ o.O'
                      |  scary questions." -- Jules                =(___)=
                      |                                               U




More information about the Ale mailing list