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?
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.
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
\14in lieu of\fso thegawklinter wouldn't complain all the time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With