Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
looking for a module
#3
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:
# 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
Reply


Messages In This Thread
looking for a module - by Skaperen - May-17-2018, 01:10 AM
RE: looking for a module - by snippsat - May-17-2018, 06:23 PM
RE: looking for a module - by ljmetzger - May-17-2018, 08:05 PM
RE: looking for a module - by Gribouillis - May-17-2018, 10:14 PM
RE: looking for a module - by Skaperen - May-18-2018, 02:08 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020