1

I have a file that I'm trying to run a "sed" command on, but I'm having trouble executing it within Python 3.10.1 while I'm running it on Cygwin 3.5.1.

The file I'm working on is very simple, it looks like this:

(Distance competency)
 1. Approximately how long does it take for light from the Sun to reach Earth?

 1 8 minutes 
 2 10 minutes 
 3 6 minutes

There is a space at the beginning of each line that I'm trying to get rid of, a relatively simple task for sed and a regex search and replace using this:

sed -i 's/^[ \t]*//g' ./myFile

When I run this at the Cygwin command line, I get exactly what I want, however I'm writing this in a Python script, and when I execute the following lines:

sedStatement = "sed -i 's/^[ \t]*//g' ./myFile"
os.system(sedStatement)

I get the following output:

(Distancecompetency) 
1.ApproximatelyhowlongdoesittakeforlightfromtheSuntoreachEarth?

18minutes
210minutes
36minutes

So instead of the caret "^" being recognized at all, it looks like it's being ignored and all of the spaces are being replaced with nothing, when what I wanted replaced was "the beginning of the line"+"space" with "nothing". So it looks like this...

(Distance competency)
1. Approximately how long does it take for light from the Sun to reach Earth?

1 8 minutes
2 10 minutes
3 6 minutes

Does anyone know what I'm doing wrong or what's causing this? I noticed I had a "^M" as an end of line marker, but I'm not sure that's the issue. I went ahead and installed "dos2unix" and ran this command, but it didn't get rid of the "^M" end of line markers.

    unix2dos -iso -n myFile myFile2

Any help would be appreciated, I'm still relatively new to Python.

Brandon
  • 11
  • 1
  • idk why the `^` would be ignored but in regards to just the sed command - a) get rid of the `g` since you want to do 1 replacement, b) change `/^[ \t]/` to just `/ /` since you know each line starts with a single blank char and THAT is what you want to remove. Also, you ran `unix2dos` when what you should have run is `dos2unix`, – Ed Morton Jan 12 '22 at 21:28
  • I couldn't reproduce the problem, though it's likely the line endings did have something to do with it, except you want to be running `dos2unix` not `unix2dos`. But if you're using Python why even run sed with os.system? Python already has the facilities for you to do this. Also note you should have use a "raw" string `sedStatement = "sed -i r's/^[ \t]*//g' ./myFile"` because the `\t` also means a literal tab character in python. Though this wouldn't be the problem. – Iguananaut Jan 14 '22 at 07:35

0 Answers0