scheme shell
about
download
support
resources
docu
links
 
scsh.net

Regexp Substitute File

Replace all occurrences of a regular expression within a file.

  (define (regexp-substitute/file file re . items)
    (let ((file-contents
           (call-with-input-file file
               (lambda (in) 
                 (read-string (file-size file) in)))))
      (call-with-output-file file
          (lambda (out)
            (apply regexp-substitute/global out re file-contents items)))))


A variant: perform a couple of simple string substitutions on a file (and don't worry about undefined behaviour or robustness in general, roll on, drunk, dazed, and confused, in a skimpy leather mini, your black beard untrimmed, remainders of soup and the few copper coins splashed over the boulevard). Tried in scsh 0.6.7.

 ;; substis : proper list of (from . to) pairs of strings
 (define (apply-substitutions-to-file substis fname)
   (let ((content/substis
          (with-input-from-file fname
            (lambda ()
              (fold (lambda (substi content)
                      (regexp-substitute/global #f (rx ,(car substi))
                                                content
                                                'pre (cdr substi) 'post))
                    (read-delimited "")
                    substis)))))
     (with-output-to-file fname ; truncate
       (lambda ()
         (display content/substis)))))

(define (apply-substitutions-to-files substis fnames) (for-each (lambda (fname) (apply-substitutions-to-file substis fname)) fnames))

#! Examples

(apply-substitutions-to-file '(("é" . "\" eacute \"") (">" . "\" > \"")) "../pages/demo.scm")

(apply-substitutions-to-files '(("é" . "\" eacute \"") ("É" . "\" Eacute \"") ("è" . "\" egrave \"") ("à" . "\" agrave \"") ("À" . "\" Agrave \"") ("ò" . "\" ograve \"") ("ù" . "\" ugrave \"") ("í" . "\" iacute \"") ("ß" . "\" szlig \"") ("ü" . "\" uuml \"") ("ö" . "\" ouml \"") ("ä" . "\" auml \"") ("â" . "\" acirc \"") ("ê" . "\" ecirc \"") ("«" . "\" laquo \"") ("»" . "\" raquo \"") ("“" . "\" ldquo \"") ("”" . "\" rdquo \"") ("‘" . "\" lsquo \"") ("’" . "\" rsquo \"") ("„" . "\" bdquo \"") ("—" . "\" mdash \"") ("–" . "\" 8211 \"") ("—" . "\" 8212 \"") ("“" . "\" 8220 \"") ("”" . "\" 8221 \"") (">" . "\" > \"")) (glob "../pages/*.scm")) !#


RegexpSubstituteFile - raw wiki source | code snippets archive