Page 1 of 1

sed like utility for s-expr

Posted: Thu Jul 04, 2013 7:11 am
by puoi
hi.

What is the best way to substitute s-exprs in a file?
For example: (a b c) -> (b (a a) something c), no matter how the expression is formatted.

Re: sed like utility for s-expr

Posted: Thu Jul 04, 2013 11:30 pm
by aidlt
Why not just READ s-expressions in a loop and process them? A simple example:

Code: Select all

(defun foo (in out process-sexpr)
  "Read s-expressions from the stream IN, process them one by one using the function PROCESS-SEXPR and print the results to the steram OUT."
  (do ((sexpr (read in nil :eof) (read in nil :eof)))
    ((eq sexpr :eof))
    (print (funcall process-sexpr sexpr) out)))

;;; Example: send all the s-exprs from a file to stdout.
(with-open-file (in "test.txt")
  (foo in t #'identity))

Re: sed like utility for s-expr

Posted: Fri Jul 05, 2013 6:30 am
by pjstirling
Won't that a) lose comments and extra whitespace, b) print everything upper-case?

Re: sed like utility for s-expr

Posted: Fri Jul 05, 2013 6:42 am
by Goheeca
The case can handled by readtable-case.

Re: sed like utility for s-expr

Posted: Fri Jul 05, 2013 3:07 pm
by aidlt
pjstirling wrote:Won't that a) lose comments and extra whitespace... ?
Surely that will! They are virtually non-existent. :)

Re: sed like utility for s-expr

Posted: Fri Jul 12, 2013 7:40 pm
by findinglisp
You could write your own basic reader. If the files you're processing are just basic sexprs, without fancy read-table stuff going on, then a basic reader is really pretty simple to build. You could do it such that you parse the file while retaining the comments. Not ideal, surely, but once you are able to get the file contents into memory as lists, it will be much easier to fiddle with them.