Swap characters in specific positions in strings of varying lengths

拟墨画扇 提交于 2019-12-21 05:30:15

问题


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 "."


回答1:


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'


来源:https://stackoverflow.com/questions/12551917/swap-characters-in-specific-positions-in-strings-of-varying-lengths

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!