简体   繁体   English

文件中的awk和regexp

[英]awk and regexp from file

I have a file: 我有一个文件:

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

I must print each word which contain in end /e,o,y/ letter in each 1,3,5.N string. 我必须打印每个1,3,5.N字符串中以/ e,o,y /字母结尾的每个单词。 Result must be: apple,tomato,empty. 结果必须是:apple,tomato,empty。 I can separate 1,3,5 string, but can not separate each word in string and check it 我可以分隔1,3,5字符串,但是不能分隔字符串中的每个单词并对其进行检查

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

and have in result 并有结果

first basket with apple

You can use something like 您可以使用类似

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

What it does? 它能做什么?

  • NR % 2 selects the lines 1 3 5... NR % 2选择行1 3 5 ...

  • if ($i ~ /[eoy]$/) checks if each field, wrod ends with a e or o or y if ($i ~ /[eoy]$/)检查每个字段是否以eoy结尾

Seems like you want something like this, 好像您想要这样的东西,

$ 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

To get the words only, 只说出话来,

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

Here is a gnu awk solution (due to multiple characters in RS ): 这是一个gnu awk解决方案(由于RS多个字符):

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

Here RS is set to space or newline, so it will run one and one word on each line. 在这里, RS设置为空格或换行符,因此它将在每一行上运行一个单词和一个单词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM