-   Programming (
-   -   How-to include a variable's name in a regex in awk to spot command names in absolute paths (

Didier Spaier 09-13-2012 05:06 PM

How-to include a variable's name in a regex in awk to spot command names in absolute paths
Hello all.

I am an absolute beginner in awk.

I have an awk script which look into a text file to find if and where some commands are present.

I put the name of the command I look for in an awk user variable, let's name that variable thecommand.

How to write a regex to find the absolute path of thecommand if mentioned in the text file?

Let's say if I look into the third field of each record, for instance. This doesn't work:

$3 ~ /^\/(.+\/)*thecommand/
Should I quote thecommand in some way, or what?

Or how can I extract the last word from the path, to be able to compare it with thecommand?

EDIT. I found a solution (not including the variable's name in the regex but checking that it's the last word of the path):

$3 ~ /^\/(.+\/)*.*/  && length(thecommand) + index($3,thecommand) == length($3)+1
PS Still, I would be interested to know how to include a variable's name in a regex...

grail 09-13-2012 10:57 PM

// for a standard regex

"" for a computed regex


$3 ~ "^\/(.+\/)*"thecommand

Didier Spaier 09-14-2012 12:54 AM

Thanks grail. IIUC I have to double quote the first part then to concatenate it with the variable (computed as a string) to build the final regex.

I have a warning with your solution :

awk: ligne de commande :1: avertissement : séquence d'échappement « \/ » traitée comme un simple « / »
though that doesn't seem to hurt. Sorry that the warning be in French, it's gettext's fault ;)

Then I rewrote it this way:

$2 ~ "^/(.+/)*"thecommand"$"
and it works as well, with no warning.

I had read, but not really understood, the manual page about dynamic regex. I hope it's only because English is not my native language :o

EDIT I eventually appended "$" after thecommand, else a pattern including thecommand as a subdirectory would have matched as well.

grail 09-14-2012 05:05 AM

It is a little tricky but you seem to be on to it :)

Also the warning about the escaped slash is the same as other languages where once in double quotes you need to escape the escape
if you wish to use it to escape something else. Hence why the final solution works just fine :)

All times are GMT -5. The time now is 01:06 AM.