Skip to content

Commit

Permalink
find_and_replace_regex
Browse files Browse the repository at this point in the history
  • Loading branch information
SmartManoj committed Oct 17, 2024
1 parent 633c17a commit b537e36
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion openhands/runtime/plugins/agent_skills/file_ops/file_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"""

import os
import re
import shutil
import subprocess
import sys
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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(
Expand Down

0 comments on commit b537e36

Please sign in to comment.