bash 如何使用 grep 和 regex 匹配特定长度的单词?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32759707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use grep and regex to match a word with specific length?
提问by BubbleMonster
I'm using Linux's terminal and i've got a wordlist which has words like:
我正在使用 Linux 的终端,我有一个单词列表,其中包含以下单词:
filers
filing
filler
filter
finance
funky
fun
finally
futuristic
fantasy
fabulous
fill
fine
And I want to do a grep and a regex to match the find words with the first two letters "fi" and only show the word if it's 6 characters in total.
我想做一个 grep 和一个正则表达式来匹配查找单词与前两个字母“fi”,并且只显示总共 6 个字符的单词。
I've tried:
我试过了:
cat wordlist | grep "^fi"
This shows the words beginning with fi.
这显示了以 fi 开头的单词。
I've then tried:
然后我尝试过:
cat wordlist | grep -e "^fi{6}"
cat wordlist | grep -e "^fi{0..6}"
and plenty more, but it's not bring back any results. Can anyone point me in the right direction?
还有更多,但它不会带回任何结果。任何人都可以指出我正确的方向吗?
回答by choroba
It's fi
and four more characters:
它fi
和另外四个字符:
grep '^fi....$'
or shorter
或更短
grep '^fi.\{4\}$'
or
或者
grep -E '^fi.{4}$'
$
matches at the end of line.
$
匹配行尾。
回答by Zoltan Ersek
Solution:
解决方案:
cat wordlist | grep -e "^fi.{4}$"
Your try:
你的尝试:
cat wordlist | grep -e "^fi{6}"
This means f and i six times, the dot added above means any charater, so it's fi and any character 4 times. I've also put an $ to mark the end of the line.
这意味着 f 和 i 六次,上面添加的点表示任何字符,所以它是 fi 和任何字符 4 次。我还放了一个 $ 来标记该行的结尾。
回答by Maroun
Try this:
尝试这个:
grep -P "^fi.{4,}"
Note that since you already have "fi", you only need at least 4 more characters.
请注意,由于您已经有了“fi”,因此您只需要至少 4 个字符。
.
denotes any character, and {4,}
is to match that character 4 or more times.
.
表示任何字符,并且{4,}
要匹配该字符 4 次或更多次。
If you write grep -e "^fi{6}"
as you did in your example, you're trying to match strings beginning with f
, followed by 6 i
s.
如果您grep -e "^fi{6}"
像在示例中那样编写,您将尝试匹配以 开头f
,后跟 6i
秒的字符串。