Skip to content

Commit 0147500

Browse files
committed
In-place replacement in file creates and removes back-up file
1 parent 7ebdd5f commit 0147500

3 files changed

Lines changed: 15 additions & 3 deletions

File tree

exputil/shell.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -252,12 +252,12 @@ def copy_file(self, source_file, target_path):
252252
return self.perfect_exec("scp %s %s" % (source_file, target_path))
253253

254254
def sed_replace_in_file_plain(self, target_file, search_term, replace_term):
255-
return self.perfect_exec("sed -i "
255+
return self.perfect_exec("sed -i'.original' "
256256
"'s/"
257257
+ re.escape(search_term).replace("/", "\\/")
258258
+ "/"
259259
+ replace_term.replace("\\", "\\\\").replace("/", "\\/").replace("&", "\\&")
260-
+ "/g' " + target_file)
260+
+ "/g' " + target_file + "; rm " + target_file + ".original")
261261

262262
def path_exists(self, path):
263263
res = self.valid_exec("if [ -d \"%s\" ]; then exit 0; else exit 1; fi" % path.replace('"', '\\"'))

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919
setup(
2020
name='exputil',
21-
version='1.5',
21+
version='1.6',
2222
description="Experiment utilities",
2323
license="Apache 2.0",
2424
python_requires='>=3.7',

tests/test_shell_file_dir.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ def test_file(self):
3030
local_shell.write_file("temp/test.txt", "Test")
3131
self.assertTrue(local_shell.file_exists("temp/test.txt"))
3232
self.assertEqual("Test", local_shell.read_file("temp/test.txt").strip())
33+
local_shell.sed_replace_in_file_plain("temp/test.txt", "Tes", "ABc")
34+
self.assertEqual("ABct", local_shell.read_file("temp/test.txt").strip())
3335
with open("temp/test.txt", "w+") as f:
3436
writer = InstantWriter(f)
3537
writer.write("Ano/.ther testno/.ther")
@@ -49,6 +51,16 @@ def test_file(self):
4951
self.assertTrue(True)
5052
local_shell.remove_recursive("temp")
5153

54+
def test_sed_replace(self):
55+
local_shell = LocalShell()
56+
local_shell.remove_force("temp")
57+
local_shell.make_full_dir("temp")
58+
local_shell.write_file("temp/testA.txt", "This is a blue world blue world")
59+
local_shell.sed_replace_in_file_plain("temp/testA.txt", "blue world", "green planet")
60+
self.assertEqual("This is a green planet green planet", local_shell.read_file("temp/testA.txt").strip())
61+
local_shell.remove("temp/testA.txt")
62+
local_shell.remove_recursive("temp")
63+
5264
def test_dir(self):
5365
local_shell = LocalShell()
5466
local_shell.make_full_dir("temp")

0 commit comments

Comments
 (0)