ACiD GRiM
ACiD GRiM

Reputation: 83

Swap characters in specific positions in strings of varying lengths

I've been trying to learn sed and the examples I've found here are for swapping dates from 05082012 to 20120805 and I'm having trouble adapting them to my current need.

I need to convert an IP address 10.4.13.22 to a reverse lookup of 22.13.4.10 for a nsupdate script. My biggest problem is the fact that sometimes each octet can change lengths e.g. 10.4.13.2 and 10.19.8.126

Thanks for any help!

echo 10.0.2.99 | sed 's/\(....\)\(....\)/\2\1/'

this is currently what I've tried, just based off another question here, but since the examples don't provide much explanation as to what .... means, Im having trouble understanding what it does.

This is the output of that command .2.910.09 and I am expecting 99.2.0.10

Directly, I want to rearrange each "section" that is separated by a "."

Upvotes: 4

Views: 1841

Answers (1)

Lev Levitsky
Lev Levitsky

Reputation: 65791

A "bruteforce" method to "reverse" an IPv4 address would be:

sed 's/\([0-9]\+\)\.\([0-9]\+\)\.\([0-9]\+\)\.\([0-9]\+\)/\4.\3.\2.\1/g'

or, for GNU sed,

sed -r 's/([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)/\4.\3.\2.\1/g'

Upvotes: 6

Related Questions