osslip25
Q2import os
import re
def search_file(filename, pattern):
try:
with open(filename, 'r') as file:
for line_number, line in enumerate(file, start=1):
if re.search(pattern, line):
print(f"Pattern found in {filename} at line {line_number}: {line.strip()}")
return
print(f"Pattern not found in {filename}")
except FileNotFoundError:
print(f"File not found: {filename}")
except Exception as e:
print(f"An error occurred: {e}")
def main():
while True:
command = input("myshell$ ")
tokens = command.split()
if not tokens:
continue
if tokens[0] == 'search' and len(tokens) == 4 and tokens[1] == 'f':
_, _, filename, pattern = tokens
search_file(filename, pattern)
elif tokens[0] == 'exit':
break
else:
# Execute other commands
try:
pid = os.fork()
if pid == 0:
# Child process
os.execvp(tokens[0], tokens)
else:
# Parent process
os.waitpid(pid, 0)
except Exception as e:
print(f"An error occurred: {e}")
if name == "main":
main()