Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep: First word in line that begins with ? and ends with?

Tags:

grep

I'm trying to do a grep command that finds all lines in a file whos first word begins "as" and whos first word also ends with "ng"

How would I go about doing this using grep?

like image 301
Barnes Noble Avatar asked Dec 05 '22 07:12

Barnes Noble


1 Answers

This should just about do it:

$ grep '^as\w*ng\b' file

Regexplanation:

^    # Matches start of the line
as   # Matches literal string as
\w   # Matches characters in word class
*    # Quantifies \w to match either zero or more
ng   # Matches literal string ng
\b   # Matches word boundary

May have missed the odd corner case.

If you only want to print the words that match and not the whole lines then use the -o option:

$ grep -o '^as\w*ng\b' file

Read man grep for all information on the available options.

like image 198
Chris Seymour Avatar answered Jun 29 '23 03:06

Chris Seymour