From be54bf3e7d88a889d05dc5849cb334a872e2d2fd Mon Sep 17 00:00:00 2001 From: "Zed A. Shaw" Date: Tue, 21 Oct 2025 11:43:17 -0400 Subject: [PATCH] Sort is now working. --- sort/.gitignore | 2 ++ sort/Makefile | 4 +++ sort/go.mod | 3 +++ sort/main.go | 66 +++++++++++++++++++++++++++++++++++++++++++++++++ sort/test.txt | 18 ++++++++++++++ 5 files changed, 93 insertions(+) create mode 100644 sort/.gitignore create mode 100644 sort/Makefile create mode 100644 sort/go.mod create mode 100644 sort/main.go create mode 100644 sort/test.txt diff --git a/sort/.gitignore b/sort/.gitignore new file mode 100644 index 0000000..e2fdc30 --- /dev/null +++ b/sort/.gitignore @@ -0,0 +1,2 @@ +sort +sort.exe diff --git a/sort/Makefile b/sort/Makefile new file mode 100644 index 0000000..bea7546 --- /dev/null +++ b/sort/Makefile @@ -0,0 +1,4 @@ + + +build: + go build . diff --git a/sort/go.mod b/sort/go.mod new file mode 100644 index 0000000..64676b8 --- /dev/null +++ b/sort/go.mod @@ -0,0 +1,3 @@ +module lcthw.dev/go/go-coreutils/sort + +go 1.25.3 diff --git a/sort/main.go b/sort/main.go new file mode 100644 index 0000000..d832321 --- /dev/null +++ b/sort/main.go @@ -0,0 +1,66 @@ +package main + +import ( + "fmt" + "bufio" + "os" + "slices" + "flag" + "strings" + "strconv" +) + +type Opts struct { + IgnoreCase bool + Numeric bool +} + +func parse_opts() Opts { + var opts Opts + + flag.BoolVar(&opts.IgnoreCase, "f", false, "ignore case") + flag.BoolVar(&opts.Numeric, "n", false, "numeric sort") + + flag.Parse() + + return opts +} + +func numeric_sort(a string, b string) int { + a_int, a_err := strconv.Atoi(a) + b_int, b_err := strconv.Atoi(b) + + if a_err != nil || b_err != nil { + return strings.Compare(a, b) + } else { + return a_int - b_int + } +} + +func ignore_case_sort(a string, b string) int { + return strings.Compare(strings.ToLower(a), strings.ToLower(b)) +} + +func main() { + lines := make([]string, 0, 100) + opts := parse_opts() + + scan := bufio.NewScanner(os.Stdin) + + for scan.Scan() { + line := scan.Text() + lines = append(lines, line) + } + + if opts.Numeric { + slices.SortFunc(lines, numeric_sort) + } else if opts.IgnoreCase{ + slices.SortFunc(lines, ignore_case_sort) + } else { + slices.Sort(lines) + } + + for _, line := range lines { + fmt.Println(line) + } +} diff --git a/sort/test.txt b/sort/test.txt new file mode 100644 index 0000000..224008c --- /dev/null +++ b/sort/test.txt @@ -0,0 +1,18 @@ +head +numfmt +od +sha512sum +sort +starter +LICENSE +outline.txt +README.md +stat +tail +tr +uniq +cat +date +du +wc +.gitignore