Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk: function to escape regex operators from a string

Tags:

regex

bash

awk

gawk

Need a function to escape a string containing regex expression operators in an awk script.

I came across this 'ugly' solution:

function escape_string( str )
{
    gsub( /\\/, "\\\\",  str );
    gsub( /\./, "\\.", str );
    gsub( /\^/, "\\^", str );
    gsub( /\$/, "\\$", str );
    gsub( /\*/, "\\*", str );
    gsub( /\+/, "\\+", str );
    gsub( /\?/, "\\?", str );
    gsub( /\(/, "\\(", str );
    gsub( /\)/, "\\)", str );
    gsub( /\[/, "\\[", str );
    gsub( /\]/, "\\]", str );
    gsub( /\{/, "\\{", str );
    gsub( /\}/, "\\}", str );
    gsub( /\|/, "\\|", str );

    return str;
}

Any better ideas?

like image 722
Lacobus Avatar asked Jul 27 '26 01:07

Lacobus


2 Answers

You can just use single gsub using a character class like this:

function escape_string( str ) {
   gsub(/[\\.^$(){}\[\]|*+?]/, "\\\\&", str)
   return str
}

& is back-reference to the matched string and \\\\ is for escaping the match.

like image 83
anubhava Avatar answered Jul 29 '26 18:07

anubhava


I use this small util function that escapes far more than needed, but makes life a lot easier by using character ranges :


 # Functions, listed alphabetically

 1 function __(_) {

       gsub("[!-/:-@[-\140{-~]", "[&]", _)  # I use \140 cuz I dont like random  
       gsub(/\^|\\/, "\\\\&", _)            # unpaired backticks dangling in my code

       return _
   }

   [!]["][#][$][%][&]['][(][)][*][+][,][-][.][/]
  0123456789                  [:][;][<][=][>][?]

 [@]ABCDEFGHIJKLMNOPQRSTUVWXYZ [[][\\][]][\^][_]
 [`]abcdefghijklmnopqrstuvwxyz [{][|] [}] [~]

Placing them all inside individual bracket expressions prevents any accidental interpretation of adjoining chars.

I have a more complex version that also escape the recognized sequences :

 [\a][\b][\t][\n][\v][\14][\r]

I use \14 in lieu of \f so the gawk linter wouldn't complain all the time.

like image 39
RARE Kpop Manifesto Avatar answered Jul 29 '26 17:07

RARE Kpop Manifesto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!