I want to write a python script that can find lines matching some patterns in a file and delete those lines.
` #!/usr/bin/env python3
import sys
def remove_lines(filename, patterns):
# Try to open the file and read lines
try:
with open(filename, 'r') as file:
lines = file.readlines()
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
sys.exit(1)
# Filter lines that do not contain any of the patterns
new_lines = [line for line in lines if all(pattern not in line for pattern in patterns)]
# Write the filtered lines back to the file
with open(filename, 'w') as file:
file.writelines(new_lines)
print(f"Updated '{filename}' by removing lines containing the specified patterns.")
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Usage: remove_lines.py <filename> <pattern1> [pattern2] ... [patternN]")
sys.exit(1)
filename = sys.argv[1]
patterns = sys.argv[2:]
remove_lines(filename, patterns)`
New contributor
Libo Sun is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.