File Search and Replace

This forum allows you to share scripts with other Zeus users. Please do not post bug reports, feature requests or questions to this forum, but rather use it exclusively for posting scripts or for the discussion of scripts that have been posted.
Post Reply
jussij
Site Admin
Posts: 2436
Joined: Fri Aug 13, 2004 5:10 pm

File Search and Replace

Post by jussij » Mon Oct 10, 2011 4:52 am

The following Zeus Python macro will do a regular expression search and replace operation over the entire contents of a text file.

Code: Select all

import re
import os.path
import zeus

# Python Help: http://docs.python.org/library/

def file_text_replace(input_file_name, find_text, replace_text):

    # read the entire fileinto memory
    file_data = open(input_file_name).read()

    if re.search(find_text, file_data):
        backup_file_name = input_file_name + ".bak"

        if os.path.exists(backup_file_name):
            os.remove(backup_file_name)

        os.rename(input_file_name, backup_file_name)

        o = open(input_file_name, "w")

        o.write(re.sub(find_text, replace_text, file_data))
        o.close()
        return 1

    return 0

def key_macro():
    # ask for a user provide the alignment character
    find_text, replace_text = zeus.user_input("Find:", "", "Replace:", "")

    if (len(find_text) > 0) and (len(replace_text) > 0):
        # make sure this file exists
        input_file_name = "c:\\temp\\test.txt"

        # helpful for debugging
        #zeus.message_box(0, "input_file_name: '" + input_file_name + "'\nfind_text: '" + find_text + "'\nreplace_text: '" + replace_text + "'")

        # do the search and replace
        # c:\\temp\\test.txt.bak
        if file_text_replace(input_file_name, find_text, replace_text) > 0:
            zeus.message("The changes where made to the '" + input_file_name + "' file.")
        else:
            zeus.message("The find text '" + find_text + "' was not found in the'" + input_file_name + "' file.")

    else:
        zeus.message("Operation cancelled by user.")

key_macro() # run the macro

Post Reply
kuchnie warszawa opinie

Who is online

Users browsing this forum: No registered users and 1 guest