Skip to content

Instantly share code, notes, and snippets.

@haisi
Created June 30, 2016 11:29
Show Gist options
  • Select an option

  • Save haisi/9481cb618e7fead5fb6051c8cc7de67c to your computer and use it in GitHub Desktop.

Select an option

Save haisi/9481cb618e7fead5fb6051c8cc7de67c to your computer and use it in GitHub Desktop.

Revisions

  1. haisi created this gist Jun 30, 2016.
    32 changes: 32 additions & 0 deletions countEachChar.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    #! /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"
    }