Created
April 27, 2010 10:33
-
-
Save stilkov/380602 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns sample.grep | |
"A simple complete Clojure program." | |
(:use [clojure.contrib.io :only [read-lines]]) | |
(:gen-class)) | |
(defn make-counter [initial-value] | |
(let [current-value (atom initial-value)] | |
(fn [] | |
(swap! current-value inc)))) | |
(defn numbered-lines [lines] | |
(let [cnt (make-counter 0)] | |
(map #(vector (cnt) %) lines))) | |
(defn grep-in-file [pattern file] | |
{file (filter #(re-find pattern (second %)) (numbered-lines (read-lines file)))}) | |
(defn grep-in-files [pattern files] | |
(apply merge (map #(grep-in-file pattern %) files))) | |
(defn print-matches [matches] | |
(doseq [file-match matches] | |
(let [fname (first file-match) | |
matches (second file-match)] | |
(doseq [match matches] | |
(println (str fname ":" (first match) ":" (second match))))))) | |
(defn -main [pattern & files] | |
(if (or (nil? pattern) (empty? files)) | |
(println "Usage: grep <pattern> <file...>") | |
(do | |
(println (format "grep started with pattern %s and file(s) %s" pattern (apply str (interpose ", " files)))) | |
(print-matches (grep-in-files (re-pattern pattern) files)) | |
(println "Done.")))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment