Jef Smackner
Jef Smackner

Reputation: 29

grep regex how to get only results with one preceeding word?

My string is :

www.abc.texas.com
mail.texas.com
subdomain.xyz.cc.texas.com
www2.texas.com

I an trying to get results only with "one" word before texas.com. Expectation when I do a regex grep :

mail.texas.com
www2.texas.com

So mail & www2 are the "one" word that I'm talking about. I tried :

grep "*.texas.com", but I get all of them in results. Can someone please help ?

Upvotes: 0

Views: 93

Answers (3)

RavinderSingh13
RavinderSingh13

Reputation: 133760

With your shown samples, please try following awk code.

awk -F'.' 'NF==3 && $2=="texas" && $3=="com"'  Input_file

Explanation: Simple making field separator as . for all the lines in awk program. Then in main program checking condition if NF==3(means number of fields in current line)are 3 AND 2nd field is texas and 3rd field is com if all 3 conditions are MET then print the line.

Upvotes: 1

Cyrus
Cyrus

Reputation: 88939

With awk:

awk 'BEGIN{FS=OFS="."} /texas.com$/ && NF==3' file

Output:

mail.texas.com
www2.texas.com

Set one dot as input and output field separator, check for texas.com at the end ($) of your line and check for three fields.

See: 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627468

You can use

grep '^[^.]*\.texas\.com'

Details:

  • ^ - start of string
  • [^.]* - zero or more chars other than a . char
  • \.texas\.com - .texas.com string (literal . char must be escaped in the regex pattern).

See the online demo:

#!/bin/bash
s='www.abc.texas.com
mail.texas.com
subdomain.xyz.cc.texas.com
www2.texas.com'
grep '^[^.]*\.texas\.com' <<< "$s"

Output:

mail.texas.com
www2.texas.com

Upvotes: 2

Related Questions