diff --git a/openhands/runtime/plugins/agent_skills/file_ops/file_ops.py b/openhands/runtime/plugins/agent_skills/file_ops/file_ops.py index f864892429..a9a7c4c447 100644 --- a/openhands/runtime/plugins/agent_skills/file_ops/file_ops.py +++ b/openhands/runtime/plugins/agent_skills/file_ops/file_ops.py @@ -26,6 +26,7 @@ """ import os +import re import shutil import subprocess import sys @@ -693,7 +694,10 @@ def find_and_replace(file_name: str, find_string: str, replace_string: str) -> N file_content = file_content.replace(find_string, replace_string) with open(file_name, 'w') as file: file.write(file_content) - print(f'[File updated successfully with {occurrences} occurrences replaced]') + if occurrences > 0: + print(f'[File updated successfully with {occurrences} occurrences replaced]') + else: + print(f'[No matches found for "{find_string}" in {file_name}]') return # # FIXME: support replacing *all* occurrences @@ -752,6 +756,24 @@ def find_and_replace(file_name: str, find_string: str, replace_string: str) -> N # print(ret_str) +def find_and_replace_regex(file_name: str, pattern: str, replacement: str) -> None: + """ + Find and replace a string in a file using regex pattern. + """ + with open(file_name, 'r+') as f: + content = f.read() + occurrences = len(re.findall(pattern, content)) + new_content = re.sub(pattern, replacement, content) + f.seek(0) + f.write(new_content) + f.truncate() + if occurrences > 0: + print(f'[File updated successfully with {occurrences} occurrences replaced]') + else: + print(f'[No matches found for "{pattern}" in {file_name}]') + return + + def insert_content_before_line(file_name: str, line_number: int, content: str) -> None: """Insert content before the given line number in a file. Remeber line number start from 1.""" ret_str = _edit_file_impl(