Search code examples
linuxbashsedcygwin

sed behavior different when put into bash script


I have a bunch of python source files that I am converting to 3.4 syntax. If I use the following command: sed -r 's/^print\s(.+$)/print\(\1\)/g' 1.12.py > 1.12a.py in Cygwin it will add the required parentheses to the print commands to be syntactically correct for 3.x python. However when I try to put this into a bash script as:

#!/bin/bash

# This is a program to remove "from Tkinter import *" occurances from source code
# and to replace it with "from tkinter import *" so it will work in python 3.3, which
# is what I'm using to program the GUI in

sed -i 's/from\ Tkinter/from\ tkinter/g' *.py

# this line is supposed to add parentheses to all print statements since python 2.7 did not 
# require parentheses around print statements
for pyFiles in *.py
    do
        newPref=${pyFiles%.py}
        #echo $pyFiles
        newName="${newPref}a.py"
        sed -r 's/^print\s(.+$)/print\(\1\)/g' $pyFiles > $newName
    done

For some reason this creates the ""a.py version of all the files but it does not add the parentheses to the print statements like it does when I just execute the sed command directly. I am probably missing something obvious. Any help would be much appreciated. Thank you.


Solution

  • Change the sed command as

    sed -r 's/print\s(.+$)/print\(\1\)/g' $pyFiles > $newName

    will replace every print in the source

    • whats wrong in

    sed -r 's/^print\s(.+$)/print\(\1\)/g' $pyFiles > $newName

    ^ anchors the regex at the begining of the string. That is it matches only when the print occures at the begining of the line. Since the python followes indentation, it maynot always begin at the starting of line rather presceded by tab character \t