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

Time:01-17

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 ?

CodePudding user response:

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

CodePudding user response:

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

  •  Tags:  
  • Related