Blast from the past - replace.ex by Jiri Babor

new topic     » topic index » view thread      » older message » newer message
--  file    : replace.ex 
--  author  : jiri babor 
--  email   : jbabor@paradise.net.nz 
--  project : search & replace 
--  tool    : euphoria 2.1 
--  date    : 99-11-27 
--  version : 1.10 
 
---------------------------------------------------------------------- 
--  Usage: ex  replace  old_text  new_text  file1  file2  file3 ... -- 
---------------------------------------------------------------------- 
--  Replace all occurances of old_text string with new_text string  -- 
--  in all specified files.                                         -- 
--  Strings containing spaces must be enclosed in quotation marks!  -- 
---------------------------------------------------------------------- 
--  **************  Play safe! Back up your files!  **************  -- 
---------------------------------------------------------------------- 
 
include file.e 
 
sequence buffer, cl, filename, files, new_text, old_text 
 
procedure help(sequence error_message) 
    puts(1,"Error :  " & error_message & "\n") 
    puts(1,"Syntax:  ex  replace  old_text  new_text  file1  file2 ...\n") 
    puts(1,"Note  :  enclose text containing spaces in quotation marks.\n") 
    abort(1) 
end procedure 
 
procedure read() 
    integer f, len, n 
 
    f=open(filename,"rb") 
    if f=-1 then 
        help("Couldn't open " & filename & " !\n") 
    end if 
    n=seek(f, -1)               -- go to end of input file 
    len=where(f)                -- get length of input file in bytes 
    n=seek(f, 0)                -- go back to beginning of input file 
    buffer = repeat(0, len)     -- init buffer 
    for i=1 to len do 
        buffer[i] = getc(f)     -- read file into buffer 
    end for 
    close(f) 
end procedure -- read 
 
procedure replace_and_write() 
    integer f, i, lo, ln 
 
    f=open(filename,"wb")       -- open output file 
    lo = length(old_text) 
    ln = length(new_text) 
 
    i = match(old_text, buffer) 
    while i do 
        puts(f, buffer[1..i-1]) 
        puts(f, new_text) 
        buffer = buffer[i+lo..length(buffer)] 
        i = match(old_text, buffer) 
    end while 
    puts(f, buffer) 
    close(f)                    -- close output file 
end procedure -- replace_and_write 
 
 
-- main ------------------------------------------------------------------------ 
 
cl=command_line() 
if length(cl) < 5 then 
    help("Insufficient number of arguments!") 
end if 
 
old_text = cl[3] 
new_text = cl[4] 
files = cl[5..length(cl)] 
 
for i=1 to length(files) do 
    filename = files[i] 
    read() 
    replace_and_write() 
end for 
 
puts(1, "Done!\n") 
new topic     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu