Skip to content

Instantly share code, notes, and snippets.

@LordShedy
Created May 14, 2020 22:07
Show Gist options
  • Save LordShedy/0a119bd8778128946c17be4cd814d4a0 to your computer and use it in GitHub Desktop.
Save LordShedy/0a119bd8778128946c17be4cd814d4a0 to your computer and use it in GitHub Desktop.
Regex Find And Replace Script
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Regex Find And Replace script"""
import sys
import re
import argparse
def read_file_split_lines(data_file_path):
"""
Function to load a file and return it as an array
:param data_file_path: path to the file to be loaded
:returns: content of the file as an array if successful
"""
try:
file = open(data_file_path, "r")
except:
sys.exit("There was error while loading the file.")
else:
try:
data_file_content = file.read().splitlines()
return data_file_content
except:
sys.exit(data_file_path + " is not a valid file!")
return False
def write_file(file_name, content="", append=False):
"""
Function to (create and) write or append content into a file.
:param file_name: file_name of file to be (created and) written into
:param content: new content of the file or content to be appended
:param append: whether or not content should be appended
:returns: true if successful, false if not
"""
def __overwriteFile(file_name):
with open(file_name, 'r+') as file:
# go to the beggining
file.seek(0)
# write the new content to the file
file.write(content)
# cut it on the end of the new content
file.truncate()
# close the file
file.close()
return True
def __appendFile(file_name):
with open(file_name, 'a') as file:
# go to the end
file.seek(2)
# write the new content to the file
file.write(content)
# cut it on the end of the new content
file.truncate()
# close the file
file.close()
return True
if append is False:
try:
__overwriteFile(file_name)
except:
# the file does not exists
open(file_name, 'a').close()
try:
__overwriteFile(file_name)
except:
sys.exit("There was error while reading or writing to the file.")
return False
return False
else:
try:
__appendFile(file_name)
except:
sys.exit("There was error while reading or writing to the file.")
return False
return False
def main():
"""main"""
# construct the argument parse and parse the arguments
argument_parser = argparse.ArgumentParser()
argument_parser.add_argument("-f", "--file", required=True, help="…")
argument_parser.add_argument("-m", "--match", help="…")
argument_parser.add_argument("-M", "--match-in-line", action='store_true', help="…")
argument_parser.add_argument("-r", "--replace-with", help="…")
argument_parser.add_argument("-R", "--replace-with-in-line", action='store_true', help="…")
argument_parser.add_argument("-o", "--output", help="…")
argument_parser.add_argument("-v", "--version", action="version", version="1.0")
arguments = vars(argument_parser.parse_args())
# there needs to be at least one match argument
if arguments['match'] is None and not arguments['match_in_line']:
sys.exit("Missing an argument!")
# if there is too many arguments
if arguments['match'] is not None and arguments['match_in_line']:
sys.exit("Too many arguments! Use either -m or -M. Not both!")
elif arguments['replace_with'] is not None and arguments['replace_with_in_line']:
sys.exit("Too many arguments! Use either -r or -R. Not both!")
# load all lines of the input file
lines = read_file_split_lines(arguments['file'])
# getting MATCH argument
if arguments['match_in_line'] and arguments['match'] is None:
try:
regex_match = input("Your Regular Expression you want to search [.*]: ")
# if enter is pressed, use a default value
if regex_match == "":
regex_match = ".*"
except:
sys.exit("")
elif not arguments['match_in_line'] and arguments['match'] is not None:
regex_match = arguments['match']
# getting REPLACE argument
if arguments['replace_with_in_line'] and arguments['replace_with'] is None:
try:
regex_replace = input("Your Regular Expression you want to replace search with: ")
except:
sys.exit("")
elif not arguments['replace_with_in_line'] and arguments['replace_with'] is not None:
regex_replace = arguments['replace_with']
# printing matched regex
# making sure -r or -R was NOT specified
if not arguments['replace_with_in_line'] and arguments['replace_with'] is None:
print("Input RegExpr: “{}”.".format(regex_match))
for line in lines:
try:
print(re.search(regex_match, line).group(0))
except:
continue
# printing replaced regex
# so if -r or -R WAS specified
else:
print("Replacing: “{}” with “{}”.".format(regex_match, regex_replace))
output_file_content = []
for line in lines:
try:
replacement = re.sub(regex_match, regex_replace, line)
output_file_content.append(replacement)
print(replacement)
except:
continue
# saving output into file
if arguments['output'] is not None:
output_file_path = arguments['output']
try:
content = '\n'.join(output_file_content) + "\n"
write_file(output_file_path, content)
except:
sys.exit("Error while saving output into file!")
else:
print("The output was stored into {}".format(output_file_path))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment