Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

grep

bash

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?

like image 555
BubbleMonster Avatar asked Sep 17 '25 10:09

BubbleMonster


2 Answers

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.

like image 190
choroba Avatar answered Sep 20 '25 01:09

choroba


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.

like image 38
Zoltan Ersek Avatar answered Sep 20 '25 01:09

Zoltan Ersek