Page 1 of 1

Want a replacemet script

Posted: Mon May 22, 2006 4:40 am
by aron
Hi I'm quite new to this newLISP thing, but I was thinking mabe make a good replacement script/program, someone maybe alredy done one?

This is what I want:

Arguments:
Start string, End String, Replace string/textfile, file_list_to_replace_in

Description:
Replaces everyting betwean Start string and End string with the text from the replace string/textfile in all files from the file list and on all places in those files.

Some kind of example:

Code: Select all

(replace-strings '<div class="thing" id="start">' '<!-- end of start -->' 'start.txt' ('index.html' 'page1.html' 'page3.html'))
Replaces everyting betwean all <div class="thing" id="start"> and <!-- end of start --> with the text from the start.txt in index.html,page1.html and page3.html.

Mabe make an option with a target file were a new file is created instead of changing the first one... this sounds easier.

All ideeas are wery appreciateed

Re: Want a replacemet script

Posted: Mon May 22, 2006 8:50 am
by HJH
aron wrote:
All ideeas are wery appreciateed
Well, perhaps
http://www.newlisp.org/DesignPatterns.h ... processing

is a start.

--HJH

Posted: Mon May 22, 2006 11:03 am
by Lutz
This is more or less what you want:

Code: Select all

(define (replace-string start-str end-str repl-str file-list)
    (dolist (fle (file-list))
        (set 'page (read-file fle))
        (replace (append start-str "(.*?)" end-str) ; regular expr. pattern
                 page                               ; text file
                (append start-str repl-str end-str) ; the replacement text
                        0)    ; regex option number
        (write-file fle page) ; write file back todisk
    )
)
I have not tried it, but think it contains all the important elements. The newLISP 'replace' function does all the work in the replacement part, appendind 'start-str', 'repl-str', 'end-st' to form the new string. I assume that 'start-str' and 'end-str' where also part of the replacement.

The function shown iterates over files and only does the work for one string to replace 'repl-str'. You could have another 'dolist' inside the first one for the files to iterate over different versions of 'rep-str'.

Lutz

ps: the link HJH gave you describes the same 'replace' techique of doing the work in the replacement expression to collect links in a web-page.

Posted: Mon May 22, 2006 2:05 pm
by aron
Thanks for the code Lutz, I still need some time to grasp it but it looks very nice. testing.. testing

Posted: Mon May 22, 2006 6:50 pm
by cormullion
I just tested your code, Lutz (a job that I can do easier than write the code in the first place!). I think:

Code: Select all

(dolist (fle (file-list))
should be

Code: Select all

(dolist (fle file-list)
With that typo (?) fixed, the code worked perfectly! What's left is just a question of passing a list of pukka file-names. I used (directory) and (real-path), but the OP's MMV.