Grep with number of caractere

maelamrani

Member
Credits
141
Hello,
How to grep by number of caractere
for exp : if i wanna grep for file with 5 caractere like momos
how can i do that ?
ls | grep -E [a-z]\{5\}
kind regards
 


JasKinasis

Well-Known Member
Credits
1,193
I think you've almost answered your own question there.
NOTE: egrep is the same as grep -E

What you have there:
ls | egrep [a-z]{5}

That will match any file that has a 5 letter name with all lowercase characters. But it will also match any files that have more than 5 lowercase characters.

If you only want matches that exactly match the expression, then you can either surround the expression with ^ and $
e.g.
ls | egrep ^[a-z]{5}$

The above will match all files that contain exactly 5 lowercase letters.

OR
Another way of doing exactly the same thing is to use greps -x option.
e.g.
ls | egrep -x [a-z]{5}

Above will match all files that contain exactly 5 lowercase letters.
Either of those will do what you want.

But if you want to include any valid uppercase, or lowercase alphabetic, or numeric digits, you could use a character class.
e.g.
ls | egrep -x [[:alnum:]]{5}

The above matches all files that contain exactly 5 characters (uppercase, lowercase, or numeric characters for the environments current LOCALE setting)

Another way to do it would be:
ls | egrep -x .{5}
Which would match all 5 letter file-names, regardless of which characters were used.
 
Last edited:


Members online


Top