3

I'm trying to get the name of a DNS server 4.2.2.1.

Using host 4.2.2.1 I get this output:

1.2.2.4.in-addr.arpa domain name pointer a.resolvers.level3.net

in my script, I do this as:

name="$($host $server)"

How can I use sed/awk on $name to only get the a.resolvers.level3.net, keeping in mind that I'll use this on completely different servers so I can't just grep a.resolvers out of the variable?

  • 2
    I assume the name="$($host $server)" is a typoand you're actually using name="$(host $server)", right? Also, I removed a trailing . from your host output since that looked like a typo. Please confirm that it was indeed not supposed to be there. – terdon May 3 '17 at 9:11
  • 1
    @terdon DNS allows a trailing dot in names, and indeed host outputs them. – JoL May 3 '17 at 18:20
  • @jlmg ah, thanks, I didn't know that. – terdon May 3 '17 at 21:47
  • First result in Google search: stackoverflow.com/questions/12426659/… – Julien Lopez May 4 '17 at 7:03
11

Another option is to slice the string :

echo ${name##* }

This will slice the string and keep the part starting from the last space to the end.

${name <-- from name  
  ##   <-- trim the front  
  *    <-- matches anything  
  ' '  <-- until the last ' '  
 }  
3

The simplest thing to do would be to use awk and tell it to print the last field:

$ echo "$name" | awk '{print $NF}'
a.resolvers.level3.net

Of course, if all you need is the server's IP, you may as well get that into name in the first place so you don't need to process it later:

name=$(host $server | awk '{print $NF}')
3
name=$(host "$server" | grep -o '[^[:space:]]*$')

will select the trailing portion of the host command's output.

3

Just putting a sed alternative as well. This will print last column from a string separated by whitespaces.

 sed 's/.*[[:space:]]\(.*\)$/\1/'

I tested it for cases where a.resolvers.level3.net is the only string in the $name variable and it works.

$ echo "$name"
1.2.2.4.in-addr.arpa domain name pointer a.resolvers.level3.net
$
$ echo "$name"|sed 's/.*[[:space:]]\(.*\)$/\1/'
a.resolvers.level3.net
$
$ name="a.resolvers.level3.net"
$ echo "$name"|sed 's/.*[[:space:]]\(.*\)$/\1/'
a.resolvers.level3.net
$
3

A far shorter answer, involving no string manipulation at all, is

dig +short -x 4.2.2.1

which displays

a.resolvers.level3.net.

and nothing more. Of course you have to have dig installed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.