diff --git a/changelog/61944.fixed b/changelog/61944.fixed new file mode 100644 index 000000000000..d25536519fb4 --- /dev/null +++ b/changelog/61944.fixed @@ -0,0 +1 @@ +fixed error when using backslash literal in file.replace diff --git a/salt/modules/file.py b/salt/modules/file.py index 9cfc73e49591..818f0104df18 100644 --- a/salt/modules/file.py +++ b/salt/modules/file.py @@ -2563,7 +2563,7 @@ def replace( else: result, nrepl = re.subn( cpattern, - repl.replace("\\", "\\\\") if backslash_literal else repl, + repl.replace(b"\\", b"\\\\") if backslash_literal else repl, r_data, count, ) @@ -2624,7 +2624,7 @@ def replace( r_data = mmap.mmap(r_file.fileno(), 0, access=mmap.ACCESS_READ) result, nrepl = re.subn( cpattern, - repl.replace("\\", "\\\\") if backslash_literal else repl, + repl.replace(b"\\", b"\\\\") if backslash_literal else repl, r_data, count, ) diff --git a/tests/pytests/functional/modules/file/test_replace.py b/tests/pytests/functional/modules/file/test_replace.py index 962db6d59264..3be41d0661d3 100644 --- a/tests/pytests/functional/modules/file/test_replace.py +++ b/tests/pytests/functional/modules/file/test_replace.py @@ -205,3 +205,8 @@ def test_replace_no_modify_time_update_on_no_change(file, multiline_file): nmtime = os.stat(str(multiline_file)).st_mtime assert mtime == nmtime + + +def test_backslash_literal(file, multiline_file): + file.replace(str(multiline_file), r"Etiam", "Emma", backslash_literal=True) + assert "Emma" in multiline_file.read_text()