tags:

views:

69

answers:

1

This post is a two-parter. I'm trying to sort a set of ip statements that look like:

ifconfig em0 alias 172.16.80.1/28
ifconfig em0 alias 172.16.180.1/32
...
ifconfig em0 alias 172.16.1.1/32

by ip. Is it possible to return a range by using a regular expression? The following returns an error

%/172.*/sort n

and this doesn't (apparently) do anything:

g/172.*/sort n

Can this even be done?

Now, I solved the range problem directly:

18,31 sort

but this sorts in ASCII-order, not numerically (wrt the ips).

ifconfig em0 alias 172.16.180.1/32
...
ifconfig em0 alias 172.16.80.1/28

and unfortunately this Vim Tip tip doesn't work:

18,31 sort n

In fact, it does nothing; sorting on the original list leaves the original order intact. So even if returning a range via regular expressions is impossible, how do I sort these lines numerically?

UPDATE The following works:

18,31 !sort -n -t . -k 3,3 -k 4,4

(I only need to sort on the last two two bytes.)

+1  A: 

You can specify a regex for the beginning line and a regex for the ending line of a range. If you had this file:

foo
bar
ifconfig em0 alias 172.16.80.1/28
ifconfig em0 alias 172.16.55.1/28
ifconfig em0 alias 172.16.180.1/28
ifconfig em0 alias 172.16.1.1/32
baz
quux

You could sort the lines with IP addresses like this:

:/172/,/baz/-1sort

This says "start at the first line that matches /172/, end one line above the first line that matches /baz/". You might come up with a more clever regex depending upon your file's contents.

I don't know how to sort IP addresses in Vim in one pass. But if you have access to GNU sort, you could do it something like this (as per this article):

:/172/,/baz/-1!sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4

That'll sort them numerically. Not sure what you mean by "lexicographically" with regards to IP addresses.

Regarding :sort and :g, the Vim help at :h :sort says:

Note that using ":sort" with ":global" doesn't sort the matching lines, it's quite useless.

Brian Carper
Lexicographic is incorrect--I should have said numeric (I've edited). Unfortunately, I thought of your range trick too but the file is just a list of ip configuration for the start_if.<interface> file used in FreeBSD; there's nothing to use as a sentinel. Otherwise everything works!
gvkv