adilos
adilos

Reputation: 69

How can I use grep and regular expression to display names with just 3 characters

I am new to grep and UNIX. I have a sample of data and want to display all the first names that only contain three characters e.g. Lee_example. but I having some difficulty doing that. I am currently using this code cat file.txt|grep -E "[A-Z][a-z]{2}" but it is displaying all the names that contain at least 3 characters and not only 3 characters

Sample data

name number
Lee_example 1
Hector_exaple 2

Upvotes: -1

Views: 1407

Answers (3)

mehdi
mehdi

Reputation: 1

The following command can be tried out :

grep -w "..." file.txt

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 158090

With awk:

awk -F_ 'length($1)==3{print $1}'

-F_ tells awk to split the input lines by _. length($1) == 3 checks whether the first fields (the name) is 3 characters long and {print $1} prints the name in that case.

Upvotes: 0

Barmar
Barmar

Reputation: 781731

You need to match the _ after the first name.

grep -E "[A-Z][a-z]{2}_"

Upvotes: 2

Related Questions