简体   繁体   中英

Reverse IP address format with sed

I have a txt file with a list of ip addresses against domain names. eg;

1.1.168.192 example1.example1.net
2.1.168.192 example2.example2.net
3.1.168.192 example3.example3.net
.....
12.1.168.192 example12.example12.net

I can't get my sed command to change the output to;

192.168.1.1 example1.example1.net
192.168.1.2 example2.example2.net
192.168.1.3 example3.example3.net
....
192.168.1.12 example12.example12.net

sed command i'm using is

sed -r 's/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/\4.\3.\2.\1/'

using it as

cat filename | sed -r 's/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/\4.\3.\2.\1/'

The only problem is that you've included an anchor $ in your pattern, which tries to match the end of each line but fails. You just need to remove it:

$ sed -r 's/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/\4.\3.\2.\1/' file
192.168.1.1 example1.example1.net
192.168.1.2 example2.example2.net
192.168.1.3 example3.example3.net

Note that I'm passing the file name as an argument to sed, thereby avoiding a useless use of cat.

awk版本

awk '{split(".",i,$1);printf "%d.%d.%d.%d %s\n",i[4],i[3],i[2],i[1],$2}' YourFile
$ sed -r 's/([^.]+)(\.[^.]+)(\.[^.]+)\.([^ ]+)/\4\3\2.\1/' file
192.168.1.1 example1.example1.net
192.168.1.2 example2.example2.net
192.168.1.3 example3.example3.net
192.168.1.12 example12.example12.net

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM