Wednesday, March 16, 2011

theflyingdutchman is badass

http://groups.google.com/group/comp.lang.lisp/browse_thread/thread/db237f82cea96697/58d5ea35e252cb8f?hl=en#58d5ea35e252cb8f


; I think this does what you are looking for.
; There are Common Lisp libraries for splitting strings and
; doing regular expressions, but this
; does not require any additional packages to be installed.

(defun linespace?(char)
(or (char= char #\Tab)
(char= char #\Space)))

(defun string-starts-with (string substring)
(let ()
(cond
((< (length string) (length substring))
nil)
( (string= substring (subseq string 0 (length substring)) )
t))))

(defun split-by-whitespace (string)
(let* (
(STARTING 0)
(TOKEN 1)
(WHITESPACE 2)
(state STARTING)
(a-token "")
(the-list '() )
(str-length (length string)) )
(dotimes (i str-length)
(if (linespace? (char string i))
(progn
(if (eq state TOKEN)
(progn
(setq the-list (cons a-token the-list))
(setq a-token "")))
(setq state WHITESPACE))
(progn
(setq a-token
(concatenate 'string a-token (string (char string
i))))
(setq state TOKEN))))
(if (eq state TOKEN)
(setq the-list (cons a-token the-list)))
(setq the-list (reverse the-list))))

(defun process-file(input-filename output-filename ip-address-start)
(let ( (input-line "")
(input-file nil)
(output-file nil)
(line-tokens '())
(counter 0))
(when (not (probe-file input-filename))
(format t "ERROR: ~s does not exist~%" input-filename)
(return-from process-file 1))
(setq input-file (open input-filename))
(setq output-file
(open output-filename :direction :output :if-
exists :supersede))
(setq input-line (read-line input-file nil))
(loop
(if (null input-line) (return))
(setq counter (+ counter 1))
; next line is fix for SBCL Windows bug
(setq input-line (string-right-trim '(#\Return) input-
line))
(setq line-tokens (split-by-whitespace input-line))
(dolist (token line-tokens)
(when (string-starts-with token ip-address-start)
(format output-file "~a~%" token)))
(setq input-line (read-line input-file nil)))
(close input-file)
(close output-file)))

(defvar *input-filename* "my_input_file.txt")
(defvar *output-filename* "my_output_file.txt")
(defvar *ip-address-start* "144.")

(process-file *input-filename* *output-filename* *ip-address-start*)

No comments: