Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple trouble with awk and regex

 echo xx y11y rrr | awk '{ if ($2 ~/y[1-5]{2}y/) print $3}'

Why I cannot get any output?

Thank you.

like image 377
znlyj Avatar asked Dec 01 '11 14:12

znlyj


People also ask

Can I use regex in awk?

In awk, regular expressions (regex) allow for dynamic and complex pattern definitions. You're not limited to searching for simple strings but also patterns within patterns.

What type of regex does awk use?

A regular expression enclosed in slashes (' / ') is an awk pattern that matches every input record whose text belongs to that set. The simplest regular expression is a sequence of letters, numbers, or both. Such a regexp matches any string that contains that sequence.

Which operator is used to match a REGK in awk?

Regular expressions can also be used in matching expressions. These expressions allow you to specify the string to match against; it need not be the entire current input record. The two operators, `~' and `!~' , perform regular expression comparisons.

How do I echo awk command?

Just use the here string approach and you can print whatever you want. The first example I give should produce exactly the output you are looking for. @ajcg the answer you were looking for is this: echo 'for pid in $(ps -ef | grep "smbd" | awk '{print \$2}'); do kill -9 $pid &> /dev/null; done' .


1 Answers

You need to enable "interval expressions" in regular expression matching by specifying either the --posix or --re-interval option.

e.g.

echo xx y11y rrr | awk --re-interval '{ if ($2 ~ /y[1-5]{2}y/) print $3}

From the man page:

--re-interval Enable the use of interval expressions in regular expression matching (see Regular Expressions, below). Interval expressions were not traditionally available in the AWK language. The POSIX standard added them, to make awk and egrep consistent with each other. However, their use is likely to break old AWK programs, so gawk only provides them if they are requested with this option, or when --posix is specified.

like image 54
dogbane Avatar answered Sep 23 '22 21:09

dogbane