Mose
Mose

Reputation: 563

How can I use sed to grab only the name server name from dig output?

I work for a company that offers webhosting and DNS services. We are trying to migrate everything over to new servers and we've often run into stale zonefiles on our servers as customers have changed their authoritative servers to someone else.

I am trying to write a script that will check whois, ns, and SOA information to determine if a domain still uses us as an authoritative server.

I am attempting to use sed to filter the output of the following to display only the nameserver without the trailing ".":

dig +noall +answer soa yahoo.com | sed 's/.*SOA\s*//' | sed 's/\.$//'

I've searched the net, but most sed command examples work on "lines" instead of "Words".

The desired output would be as follows:

$ dig +noall +answer soa yahoo.com | sed '<Some SED code here>'
ns1.yahoo.com

Any suggestions would be helpful.

Upvotes: 1

Views: 1272

Answers (3)

ghostdog74
ghostdog74

Reputation: 342263

when working with structured data, its easier to use awk

$ dig +noall +answer soa yahoo.com | awk '{sub(/.$/,"",$5);print $5}'
ns1.yahoo.com

Upvotes: 3

David
David

Reputation: 2861

Rather than using removing the part that you don't want, I would suggest using a bracketed subexpression to identify the bit that you do want, as follows:

dig +noall +answer soa yahoo.com | sed 's/.*SOA\s*//' | sed 's/^\([^ ]*\). .*/\1/g'

This searches for a string beginning with some non-space characters, followed by a dot, a space, and then the rest of the line. It replaces that pattern with just the bit before the dot (which is subexpression #1).

Upvotes: 3

Ollie Saunders
Ollie Saunders

Reputation: 8057

To count the number of words on a line:

awk '{ print NF }'

For instance:

printf 'foo bar\nbar\nfoo bar zim' | awk '{ print NF }'

Prints:

2
1
3

Upvotes: 2

Related Questions