Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/'
like image 896
user62597 Avatar asked Jan 31 '26 07:01

user62597


1 Answers

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.

like image 83
Tom Fenech Avatar answered Feb 03 '26 01:02

Tom Fenech