This is an education project that attempts to reimplement the GNU coreutils in Go. You can find the full manual here:
https://www.gnu.org/software/coreutils/manual/coreutils.html
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.
66 lines
1.1 KiB
66 lines
1.1 KiB
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"bufio"
|
|
"os"
|
|
"slices"
|
|
"flag"
|
|
"strings"
|
|
"strconv"
|
|
)
|
|
|
|
type Opts struct {
|
|
IgnoreCase bool
|
|
Numeric bool
|
|
}
|
|
|
|
func ParseOpts() 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 NumericSort(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 IgnoreCase(a string, b string) int {
|
|
return strings.Compare(strings.ToLower(a), strings.ToLower(b))
|
|
}
|
|
|
|
func main() {
|
|
lines := make([]string, 0, 100)
|
|
opts := ParseOpts()
|
|
|
|
scan := bufio.NewScanner(os.Stdin)
|
|
|
|
for scan.Scan() {
|
|
line := scan.Text()
|
|
lines = append(lines, line)
|
|
}
|
|
|
|
if opts.Numeric {
|
|
slices.SortFunc(lines, NumericSort)
|
|
} else if opts.IgnoreCase{
|
|
slices.SortFunc(lines, IgnoreCase)
|
|
} else {
|
|
slices.Sort(lines)
|
|
}
|
|
|
|
for _, line := range lines {
|
|
fmt.Println(line)
|
|
}
|
|
}
|
|
|