Skip to content

Instantly share code, notes, and snippets.

@haisi
Created June 30, 2016 11:29
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save haisi/9481cb618e7fead5fb6051c8cc7de67c to your computer and use it in GitHub Desktop.
Groovy-Script to count each character in passed file and prints them in ascending order
#! /usr/bin/env
// Example
// groovy countEachChar.groovy MY_TEXTFILE > OUT_PUT_TEXT_FILE
def printErr = System.err.&println
if (args.length == 0) {
printErr "No path is passed as an argument! Exiting!"
return;
}
File file = new File (args[0])
def map = [:]
file.eachLine { line ->
line.toCharArray().each { c ->
if (map.containsKey(c)) {
map.put(c, map[c] + 1)
} else {
map.put(c, 1)
}
}
}
// asc
map.sort { e1, e2 ->
e2.value <=> e1.value
}.each { k, v ->
println "$k $v"
}
@haisi
Copy link
Author

haisi commented Jun 30, 2016

Example output

e 373466
r 243220
i 221312
t 219503
n 216795
a 214619
  175977
s 170042
o 115455

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment