2014-11-22 62 views
0

我有一个文件:AWK和正则表达式从文件

first basket with apple 
second basket with apricota 
third basket with tomato 
fourth basket with olives 
fifth empty basket 

我必须打印包含在端/ E,O,Y /每个1,3,5.N字母串的每个单词。 结果必须是:苹果,番茄,空。 我可以单独1,3,5字符串,但不能在字符串每个字分开,并检查它

awk '{if (NR % 2 != 0); {if (/(y|e|o)$/) print $0}}' inputfile 

,并在结果

first basket with apple 

回答

1

您可以使用类似

$ awk 'NR % 2 { for (i=1; i<=NF; i++) if ($i ~ /[eoy]$/) print $i}' input 
apple 
tomato 
empty 

它做什么?

  • NR % 2选择线1 3 5 ...

  • if ($i ~ /[eoy]$/)检查每个字段,wrod与eoy

1

结束就像你想要的东西似乎像这样,

$ awk '{for(i=1;i<=NF;i++){if($i ~ /.*(e|o|y)$/){print $0}}}' file 
first basket with apple 
third basket with tomato 
fifth empty basket 

,仅保留的话,

$ awk '{for(i=1;i<=NF;i++){if($i ~ /.*(e|o|y)$/){print $i}}}' file 
apple 
tomato 
empty 
0

这里是一个gnu awk溶液(由于RS多个字符):

awk -v RS=" |\n" '/([yeo])$/' file 
apple 
tomato 
empty 

这里RS设置为空格或换行,所以它会运行一个每行有一个字。