BubbleMonster
BubbleMonster

Reputation: 1416

How can I use grep and regex to match a word with specific length?

I'm using Linux's terminal and i've got a wordlist which has words like:

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.

I've tried:

cat wordlist | grep "^fi" 

This shows the words beginning with 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?

Upvotes: 4

Views: 26027

Answers (3)

Zoltan Ersek
Zoltan Ersek

Reputation: 775

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.

Upvotes: 4

choroba
choroba

Reputation: 242323

It's fi and four more characters:

grep '^fi....$'

or shorter

grep '^fi.\{4\}$'

or

grep -E '^fi.{4}$'

$ matches at the end of line.

Upvotes: 7

Maroun
Maroun

Reputation: 96018

Try this:

grep -P "^fi.{4,}"

Note that since you already have "fi", you only need at least 4 more characters.

. denotes any character, and {4,} is to match that character 4 or more times.

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 is.

Upvotes: 2

Related Questions