1

I am writing a bash script to extract a domain out of string of the form:

....domain name example.com...

and I want to output example.com.

How can I use matching to output this domain name?

1
  • 3
    The question is too loosely defined to be answered properly. Try to think of some corner cases and describe how they should be handled. Commented Nov 5, 2012 at 21:08

4 Answers 4

2

You should better define the pattern of your domain in order to better match it in the string. After that you can use grep to match a regex describing your domain pattern:

domain=`echo "....domain name xxx.com..." | grep -om 1 -G "[^ ]*\.com"`
Sign up to request clarification or add additional context in comments.

Comments

2

Without assuming the domain name ends in ".com"

grep -oP '(?<=domain name )\S+'

meaning: look for a sequence of non-whitespace characters following the string "domain name "

Comments

1

with GNU grep

 echo "random words domain name example.com random words" | grep -oP  "domain name \K[^ ]+\.com"

Comments

0

If the the format is exactly as you say, then this will suffice:

awk '/domain name/{print $3}'

If the string is stored in a variable, you can use it as follows:

awk '/domain name/{print $3}' <<< $string_name

If the string is stored in a file with other strings, one per line:

awk '/domain name/{print $3}' < input_file > output_file

4 Comments

Thanks so much. I'm just wondering- in your second example, how does $3 tell awk to output the word that is directly following "domain name"?
It assumes they are always the first two words.
ok, is there a way to get the word directly after "domain name" if there are words prior (i.e. "... ... abc def domain name xxx.com....")?
@user1190650 there is, but it would be easier for everyone if you more explicitly defined the requirements of the problem in your original question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.