简体   繁体   English

grep正则表达式以,结束但不包含

[英]grep regex start with, end with but not containing

I'm working with grep and sed commands in textfiles within Linux. 我正在使用Linux中的文本文件中的grep和sed命令。 I'm busy playing with the Documents/Data folder and the share/dict/words document. 我正在忙着使用Documents / Data文件夹和share / dict / words文件。 I need to extract all words within the words file that begin with "q", end with "s" but do not contain "a" or "r". 我需要提取单词文件中以“q”开头的所有单词,以“s”结尾,但不包含“a”或“r”。 I've managed to get this piece of code so far: 到目前为止,我已经设法得到这段代码:

grep –n ‘\<q.*[ar]s\>’ /usr/share/dict/words

Which gives me words that shouldn't be included. 这给了我不应该包括的话。 I've tried adding a "|" 我试过加一个“|” and then grep -v to exclude those words like follows: 然后grep -v排除下面这些单词:

grep –n ‘\<q.*s\>’ /usr/share/dict/words | grep –nv ‘\<q.*[ar]s\>’ /usr/share/dict/words

This just returns all other words that don't start in "q" or end in "s" 这只返回所有其他不以“q”开头或以“s”结尾的单词

I need to extract all words within the words file that begin with "q", end with "s" but does not contain "a" or "r". 我需要提取单词文件中以“q”开头的所有单词,以“s”结尾但不包含“a”或“r”。

You need to use a negated character class : 您需要使用否定的字符类

grep -n "\<q[^ar]*s\>" /usr/share/dict/words

You may also want to refer to Regular expressions . 您可能还想引用正则表达式

The character class [^ar] matches a single charcter which is not a or r. 字符类[^ar]匹配不是a或r的单个字符。 Allow zero or more of these between q and s. 在q和s之间允许零或多个。

grep '^q[^ar]*s$' /usr/share/dict/words

Through GNU sed , 通过GNU sed

sed -n '/^q[^ar]*s$/p' file

It print all the lines that starts with q and ends with s and also it won't contain the the characters a , r inside. 它打印所有以q开头并以s结尾的行,并且它不包含字符ar inside。

Example: 例:

$ cat cc
qars
qees
qfrs
qoos
jklo
$ sed -n '/^q[^ar]*s$/p' cc
qees
qoos

Through awk , 通过awk

$ awk '/^q[^ar]*s$/ {print}' cc
qees
qoos

Thank you, I completed it the long way and worked too. 谢谢,我完成了很长的路并且也工作了。 Completely forgot about the "^" this is my method that I then attempted: 完全忘记了“^”这是我尝试的方法:

grep –in ‘\<q.*s\>’ /usr/share/dict/words | grep –inv "a" | grep -inv "r"

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

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