-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgroupBy.bat
executable file
·66 lines (55 loc) · 1.96 KB
/
groupBy.bat
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
::#! 2>/dev/null || echo "
@echo off
call scala -savecompiled %~f0 %*
goto :eof
" >//null
#!/bin/sh
exec scala -savecompiled "$0" "$@"
::!#
args match {
case Array(lineRegex) => // OK
case Array(lineRegex, "sum") => // OK
case Array(lineRegex, "avg") => // OK
case Array(lineRegex, "min") => // OK
case Array(lineRegex, "max") => // OK
case _ => {
println("""
| Group and count/sum/avg/min/max lines based on a given regex.
| Grouping is done by the first group of the regex, summing etc by the second group.
| Usage:
| groupBy "<regex>"
| groupBy "<regex>" sum
| groupBy "<regex>" avg
| groupBy "<regex>" min
| groupBy "<regex>" max
| Examples:
| (echo a1 && echo b2 && echo a3) | groupBy "([a-z])\d"
| 'a' 2
| 'b' 1
| (echo a1 && echo b2 && echo a3) | groupBy "([a-z])(\d).*" sum
| 'a' 4.0
| 'b' 2.0
| (echo a1 && echo b2 && echo a3) | groupBy "([a-z])(\d).*" avg
| 'a' 2.0
| 'b' 2.0
| (echo a1 && echo b2 && echo a3) | groupBy "([a-z])(\d).*" min
| 'a' 1.0
| 'b' 2.0
| (echo a1 && echo b2 && echo a3) | groupBy "([a-z])(\d).*" max
| 'a' 3.0
| 'b' 2.0
""".stripMargin)
exit
}
}
import scala.io._
val lines = Source.stdin.getLines.toSeq
val GroupByPattern = args(0).r
val method = if (args.length == 1) None else Some(args(1))
lines groupBy { x => (for (m <- GroupByPattern.findFirstMatchIn(x)) yield m.group(1)).mkString } foreach { case (key, values) => println("'" + key + "' " + (method match {
case Some("sum") => values.map { case GroupByPattern(a,b) => b.toDouble }.sum
case Some("avg") => values.map { case GroupByPattern(a,b) => b.toDouble }.sum / values.size
case Some("min") => values.map { case GroupByPattern(a,b) => b.toDouble }.min
case Some("max") => values.map { case GroupByPattern(a,b) => b.toDouble }.max
case None => values.size
}))}