1

I have a regex that works fine in awk, but first I need to store the regex in a shell variable

valLat="^[-+]?(([0-9]+[d])?([0-9]+['])?([0-9]*[.]?[0-9]+[\"])?|[0-9]*[.]?[0-9]+)[NnSs]?$"

then pass the shell variable to an awk variable like this

echo 39d41\'17.766\"N | awk -v valLat=$valLat '{ if ($1 ~ valLat) print $1; else print "erro" }' 39d41'17.766"N

This works, but I want do this without using a shell variable. I've tried to use the escape "\" preceding the special characters without success.

doubleDown
  • 8,048
  • 1
  • 32
  • 48
apinhal
  • 15
  • 3

3 Answers3

0

There is no way to escape single-quotes inside of single-quoted strings in bash. So you should use double-quotes for awk script.

echo 39d41\'17.766\"N | awk "{ if (\$1 ~ /^[-+]?(([0-9]+[d])?([0-9]+[\'])?([0-9]*[.]?[0-9]+[\"])?|[0-9]*[.]?[0-9]+)[NnSs]?$/ ) print \$1; else print \"error\" }"
Community
  • 1
  • 1
Nikolai Popov
  • 5,397
  • 1
  • 17
  • 18
  • 1
    No, you should never use double quotes as it makes the script much too complicated. Put the script in a file an use `awk -f` on it or use ANSI escape sequences or define a variable for he single quote. – Ed Morton Jun 27 '13 at 12:50
  • @EdMorton Is my script much complicated than yours? I don't think so. On other point of view create another file for awk one-liner is kind of complication. In case of big pieces of awk code you right. – Nikolai Popov Jun 27 '13 at 13:12
  • 1
    It's not that THAT SCRIPT is much more complicated, it's that THAT APPROACH needlessly produces much more complicated scripts as you then need to remember escape double quotes, $ signs, backslashes, etc. It's just never the right way to solve this problem when there's much simpler, more robust ways to do it. – Ed Morton Jun 27 '13 at 14:16
  • In your script, for example: I really don't know if the `$` at the end of your RE needs to be escaped or not but the `'` in the middle of the RE should not be escaped. Its probably harmless but I don't know for sure - it MAY mean `\ or '` instead of just `'`. You simply don't have to care about this kind of "special case" stuff if you just don't use double quotes as the delimiter. – Ed Morton Jun 27 '13 at 14:29
  • Thank you both, today I've learned a very basic important thing... @EdMorton your solutions turned to be the more interesting. – apinhal Jun 27 '13 at 15:50
0

Put the script in a file and use awk -f on it or use ANSI escape sequences or define a variable for the single quote, e.g. using \x27 for the single quote:

$ echo 39d41\'17.766\"N | awk '$1 ~ /^[-+]?(([0-9]+[d])?([0-9]+[\x27])?([0-9]*[.]?[0-9]+["])?|[0-9]*[.]?[0-9]+)[NnSs]?$/'
39d41'17.766"N
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

no need to "store into file" : just use octals

shell variable

valLat='^[-+]?(([0-9]+[d])?([0-9]+\47)?([0-9]*[.]?[0-9]+\42)?|[0-9]*[.]?[0-9]+)[NnSs]?$'

matching against input

echo 39d41\'17.766\"N | 
mawk -F"$valLat" NF==2
RARE Kpop Manifesto
  • 2,453
  • 3
  • 11