May-17-2018, 08:05 PM
UNIX like sed can do what you want from a Windows (or Linux) script (Tested on Windows 10 only):
sed -i "30,70 s/foo/bar/g" abc.txt (Linux may need single quotes)
sed can be run from a Python Script as follows:
I have not used sed in many years, but if several different similar edits are to be done on a group of files, my personal preference would be to use sed and a Windows Command file (or Linux script) obtaining the commands from a sed input file. I think debugging the changes would be much quicker in sed than using Python.
NOTE: Linux probably does not need a download. sed probably comes with Linux.
Lewis
sed -i "30,70 s/foo/bar/g" abc.txt (Linux may need single quotes)
sed can be run from a Python Script as follows:
# sed.exe example (sed = UNIX stream editor) # Download (Windows version) : http://unxutils.sourceforge.net/ (extract sed.exe from .zip file) # Intro and Tutorial: http://www.grymoire.com/Unix/Sed.html # Using sed from Python: https://askubuntu.com/questions/747450/how-do-i-call-a-sed-command-in-a-python-script # -i = edit in place (i.e. replace original file) # s = substitute # g = global (i.e. replace all occurrences on each line) # Windows cmd.exe call string: # sed.exe -i "30,70 s/foo/bar/g" abc.txt import subprocess myresult = subprocess.call(["sed", "-i", r"30,70 s/foo/bar/g", "abc.txt"])Anecdotal evidence suggests that native Python code is superior to sed such as snippsat's example code or similar code using regular expressions.
I have not used sed in many years, but if several different similar edits are to be done on a group of files, my personal preference would be to use sed and a Windows Command file (or Linux script) obtaining the commands from a sed input file. I think debugging the changes would be much quicker in sed than using Python.
NOTE: Linux probably does not need a download. sed probably comes with Linux.
Lewis
To paraphrase: 'Throw out your dead' code. https://www.youtube.com/watch?v=grbSQ6O6kbs Forward to 1:00