Languages and Scripting

parse a file with expressions (*)

 
SOLVED
Go to solution
support_billa
Valued Contributor

parse a file with expressions (*)

hello,

 

i have a new question to :

 

parse a file with expressions (grep)

 

the awk is perfect:

 

No, "*" is easier:
# Pattern in test.cnf
# Use == for match
awk -v entry1="${entry1}" -v entry2="${entry2}" -v var="${var}" '
($1 == "*" || $1 == entry1) &&
($2 == "*" || $2 == entry2) &&
$3 == var { print "FOUND5:", $0 }' test.cnf

 

and handle entry in "test.cnf" like:

 

* entry2

entry entry2

 

but how can i handle entries with  "characters*" like in "test.cnf" :

demo* entry

 

is it possible to handle entries with "*" and "character*" ([a-z]*) and a exact entry ?

 

regards

4 REPLIES 4
Dennis Handly
Acclaimed Contributor

Re: parse a file with expressions (*)

>demo* entry

>is it possible to handle entries with "*" and "character*" ([a-z]*) and a exact entry?

 

I'm not sure what you want?  Do you want to treat "*" as a normal character or as a shell pattern match?

Your above awk fragment treats it as a normal char but with special processing, to pretend to be a pattern.

 

If you want to do more general pattern matching, you would have to use system to invoke a shell.

Or you could convert that pattern into a regex an use awk's ERE to do the matching.

demo* (pattern) == demo.* (regex)

demo? (pattern) == demo. (regex)

support_billa
Valued Contributor

Re: parse a file with expressions (*)

hello,

 

If you want to do more general pattern matching, you would have to use system to invoke a shell.
Or you could convert that pattern into a regex an use awk's ERE to do the matching.

demo* (pattern) == demo.* (regex)
demo? (pattern) == demo. (regex)

 right, i want to extend "awk" and want to handle

"*"

"demo*"

"demo"

for example

 

"*" and "demo" is perfect with the awk , but how i handle like "demo*"

 

regards

Dennis Handly
Acclaimed Contributor
Solution

Re: parse a file with expressions (*)

>I want to extend "awk" and want to handle: "*", "demo*", "demo"

 

As I suggested, you convert the pattern to a ERE then try matching:

awk -v entry1="${entry1}" -v entry2="${entry2}" -v var="${var}" '
function to_ere(pattern) {
   # convert from *, ? pattern to ERE, add anchors
   gsub("\*", ".*", pattern)
   gsub("\?", ".", pattern)
   pattern = "^" pattern "$"
   return pattern
}
$3 == var {
   ere1 = to_ere($1)
   ere2 = to_ere($2)
   if (entry1 ~ ere1 && entry2 ~ ere2) {
      print "FOUND5:", $0
   }
}' test.cnf

support_billa
Valued Contributor

Re: parse a file with expressions (*)

thank you very much, perfect solution with ERE ( i learn every day when you post solutions)