开发者

Awk regex matching problem

I experienced a problem using regex with awk. In particular I need to find all words in a file that:

  • begin with "un";
  • are at least 6 character long
  • end with two vowel

(these conditions must be verified contemporaneously).

I've used this regex

cat file.txt | awk '{ for(k=1; k<=NF; k++) 
                         if ($k ~ /^un.{2,}[aeiouAEIOU]{2}$/ ) 
                             print $k; }'

the problem is that sometimes works and sometimes not.

I've tried 开发者_Go百科it with two files:

test.txt

unaaaiuolaa
unaaaaaa
unbbaa

file.txt

unaaaiuolaa
unarmadio

Mysteriously the regex matches all the words in the first file but only "unarmadio" in file.txt (notice that "unaaaiuolaa" is the same in both files).

May someone explain me why?


It's a very odd construction to use a loop within awk; I'd just do

awk '/^un.{2,}[aeiouAEIOU]{2}$/' < file.txt


A different approach below, if you have multiple words in a a line, use the for-loop approach given in your question (a common method to handle each item in a row given by the FS-variable). Check the length before applying the regexp, which uses a greedy operator for "any character" and then 2 identical character-classes to make sure an item ends with 2 vowels.

{ for(k=1; k<=NF; k++)  {
        if (length($k) > 5) {
            if ($k ~ /^un.*[aeiou][aeiou]$/) {
                print $k;
            }
        }
    }
}


As grok12 said, the problem was an empty space at the end of "unaaaiuolaa". Deleting it solved the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜