sed like utility for s-expr

Discussion of Common Lisp
Post Reply
puoi
Posts: 1
Joined: Thu Jul 04, 2013 7:04 am

sed like utility for s-expr

Post by puoi » Thu Jul 04, 2013 7:11 am

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.

aidlt
Posts: 19
Joined: Thu May 16, 2013 1:42 pm

Re: sed like utility for s-expr

Post by aidlt » Thu Jul 04, 2013 11:30 pm

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))

pjstirling
Posts: 166
Joined: Sun Nov 28, 2010 4:21 pm

Re: sed like utility for s-expr

Post by pjstirling » Fri Jul 05, 2013 6:30 am

Won't that a) lose comments and extra whitespace, b) print everything upper-case?

Goheeca
Posts: 271
Joined: Thu May 10, 2012 12:54 pm
Contact:

Re: sed like utility for s-expr

Post by Goheeca » Fri Jul 05, 2013 6:42 am

The case can handled by readtable-case.
cl-2dsyntax is my attempt to create a Python-like reader. My mirror of CLHS (and the dark themed version). Temporary mirrors of aferomentioned: CLHS and a dark version.

aidlt
Posts: 19
Joined: Thu May 16, 2013 1:42 pm

Re: sed like utility for s-expr

Post by aidlt » Fri Jul 05, 2013 3:07 pm

pjstirling wrote:Won't that a) lose comments and extra whitespace... ?
Surely that will! They are virtually non-existent. :)

findinglisp
Posts: 447
Joined: Sat Jun 28, 2008 7:49 am
Location: Austin, TX
Contact:

Re: sed like utility for s-expr

Post by findinglisp » Fri Jul 12, 2013 7:40 pm

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.
Cheers, Dave
Slowly but surely the world is finding Lisp. http://www.findinglisp.com/blog/

Post Reply