Jesse
Jesse

Reputation: 996

Use only sed/BASH to convert expanded IPv6 into reverse nibble arpa for PTR

I have many IPv6 addresses I work with, but let's say today it's: 2001:abc::1

I already can expand it using BASH to: 2001:0abc:0000:0000:0000:0000:0000:0001

I need to take that expanded IPv6 and reverse it into a nibble (plus the arpa string) for my PTR, so it looks like this:

1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.c.b.a.0.1.0.0.2.ip6.arpa

I'll allow awk or other lower-stack answers to benefit the community, BASH and functions are okay, but a one-line sed would rock my world.


Note: There was discussion about this being a "real problem". My scripts only use sed, no awk anywhere, and lean toward /sh more than /bash. I consider the skills needed to maintain the scripts part of a de facto "dependency" and I avoid awk for that reason. However, to be useful to the community, awk answers should be welcome here. A BASH function not using awk would also be welcome.

Upvotes: 0

Views: 1031

Answers (3)

Ed Morton
Ed Morton

Reputation: 204558

Using any awk in any shell on any UNIX system:

$ awk '{
    gsub(/:/,"")
    for (i=length($0); i>0; i--) {
        printf "%s.", substr($0,i,1)
    }
    print "ip6.arpa"
}' file
1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.c.b.a.0.1.0.0.2.ip6.arpa

Upvotes: 2

Benjamin W.
Benjamin W.

Reputation: 52506

A GNU sed one-liner, probably mostly to demonstrate how you shouldn't use sed for this:

sed 's/://g;s/^.*$/\n&\n/;tx;:x;s/\(\n.\)\(.*\)\(.\n\)/\3\2\1/;tx;s/\n//g;s/\(.\)/\1./g;s/$/ip6.arpa/'

Broken up and commented:

# Remove all the colons
s/://g

# Embed line between two newlines
s/^.*$/\n&\n/

# Reset flag tested by t
tx

# Label to jump to
:x

# Swap two characters
s/\(\n.\)\(.*\)\(.\n\)/\3\2\1/

# Jump to label if substitution did something
tx

# Remove newlines
s/\n//g

# Insert period after each character
s/\(.\)/\1./g

# Append rest of desired string
s/$/ip6.arpa/

The line reversal technique is taken from the GNU sed manual.

The only thing in there that actually requires GNU sed is inserting newlines with just \n; if instead of s/^.*$/\n&\n/, you use literal newlines as in

s/^.*$/\
&\
/

the script should run with any sed.

Upvotes: 2

Charles Duffy
Charles Duffy

Reputation: 295815

rarpa() {
  local idx s=${1//:}
  for (( idx=${#s} - 1; idx>=0; idx-- )); do
    printf '%s.' "${s:$idx:1}"
  done
  printf 'ip6.arpa\n'
}

rarpa '2001:0abc:0000:0000:0000:0000:0000:0001'

...emits as output:

1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.c.b.a.0.1.0.0.2.ip6.arpa

Upvotes: 2

Related Questions