grep with regular expression

Hi, guys. I have one question, hope somebody can give me a hand

I have a file called passwd, the contents of it arebelow:

***********************
...
goldsimj:x:5008:200:
goldsij2:x:5009:200:
whitej:x:5010:201:
brownj:x:5011:202:
goldsij3:x:5012:204:
greyp:x:5013:203:
...
**********************

I want to grep all the lines which has "goldsi" at the beginning, a "j" at position 7 or 8 in the first column and 200 in column 4.

I used the following code:

grep -G "^goldsi?j?:x:[0-9]{4,}:200"

However, it doesn't work. Does anybody know what is wrong with my code OR provide better solution?

Thank you very much for your time in advance

-Keyang

awk -F: '/^goldsi/ && substr($1,7,2) ~ /j/ && $4 == 200' passwd

Hi, cfajohnson.

Thank you very much for you reply. The answer is short but confused :slight_smile:

-Keyang

I joined this forum to learn more ways to do things using sed and awk. I'm going to break this out and cfajohnson can correct me as needed.

awk # call awk utility
-F: # break line into fields using colon as a delimiter
'/^goldsi/ # search for lines begining with goldsi
&& substr($1,7,2) ~ /j/ # AND containing a 'j' in positions 7 or 2 of field 1
&& $4 == 200' # AND containing 200 in field 4
passwd # in file passwd

Hi, idapswandog.

Thanks for the explaination. :slight_smile:

But the line below I am not quite agree with you.

&& substr($1,7,2) ~ /j/ # AND containing a 'j' in positions 7 or 2 of field 1

This line might mean get a substring from field 1 at position 7 for 2 characters long.

-Keyang

No, substr($1,7,2) returns a substring of $1 that is 2 characters long beginning at the 7th character, i.e., the 7th and 8th characters.

Thanks for the explanation cfajohnson, still learning... so do I get a 95% :wink: