#!usr/bin/python

# Import lib
import sys
import time
import os
import signal

# Sub function
def call_help():
    print("./script.py <filename> <key> [newkey]\n")
    print("with:\n")
    print(" filename: file location & name\n")
    print(" key: string need to find\n")
    print(" newkey: string will replace for key (optional)\n")

def search_n_replace(file, key, newkey):
    if key in file:
        # Loop to find key and report location
        print("Input : " + file)
        pos = file.find(key);
        while pos >= 0:
            print("Found " + key + " at " + str(pos))
            pos = file.find(key, pos + 1);
        
        # Replace all key in file
        file = file.replace(key, newkey)
        return file
    else:
        print("Cannot find key " + key + " in " + file)
    
# Main function
# This condition to make sure main call from user cmd, not from another file imported this module (this file)
#if __name__ == '__main__':
if 1:
    # Check user input: ./script.py filename key [new key]
#    if len(sys.argv) < 2:
#        call_help()
#        sys.exit(0)
#    elif len(sys.argv) < 4:
#        input_file = sys.argv[1]
#        key = sys.argv[2]
#        newkey = ""
#    elif len(sys.argv) < 5:
#        input_file = sys.argv[1]
#        key = sys.argv[2]
#        newkey = sys.argv[3]
    input_file = "Sentence search and replace"
    key = "a"
    newkey = "aa"
           
    # Check file available
#    try:
#        with open(input_file) as file:
#            pass
#    except IOError as e:
#        print("Unable to open file")
#        sys.exit(-1)
    if len(input_file) == 0 or len(key) == 0:
        print("Wrong input")

    # Call function search key in file (location printout)
    # If user input new key, replace it in file
    input_file = search_n_replace(input_file, key, newkey)
    print("Replaced => " + input_file)
    

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: