sort ip addresses in numerical order
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
634 B

2 years ago
  1. // command svsort sorts lines of text by semver at beginning of line
  2. package main
  3. import (
  4. "bufio"
  5. "bytes"
  6. "fmt"
  7. "log"
  8. "net"
  9. "os"
  10. "sort"
  11. )
  12. type lines []string
  13. func (l lines) Len() int { return len(l) }
  14. func (l lines) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
  15. func (l lines) Less(i, j int) bool {
  16. a, b := net.ParseIP(l[i]), net.ParseIP(l[j])
  17. return bytes.Compare(a, b) < 0
  18. }
  19. func main() {
  20. s := bufio.NewScanner(os.Stdin)
  21. ls := lines{}
  22. for s.Scan() {
  23. ls = append(ls, s.Text())
  24. }
  25. if err := s.Err(); err != nil {
  26. log.Fatalf("scan: %v")
  27. }
  28. sort.Sort(ls)
  29. for _, l := range ls {
  30. fmt.Printf("%v\n", l)
  31. }
  32. }