1

In a file test.py which reads:

#!/usr/bin/env python

import os
import glob

for f in glob.glob('*.txt'):
    print f

...I'd like to programatically replace:

glob.glob('*.txt')

... with:

glob.glob('*.txt')+glob.glob('*.dat') using sed.

I have tried:

sed -i "s,glob.glob('*.txt'),glob.glob('*.txt')+glob.glob('*.dat'),g" test.py

...however this does not replace the string. I have a hunch that this has to do with the use of single quotes in the string to replace and/or the interpretation of the various quotation marks in the shell itself (bash). What is going wrong?

HotDogCannon
  • 2,113
  • 11
  • 34
  • 53
  • If you have more than one place where the substitution needs to be made (if not, why not just do it by hand?), you should define a wrapper function around the call to `glob` so that there *is* only one place to change. – chepner Mar 22 '17 at 13:26

1 Answers1

2

You need to escape all special regex meta characters such as . or * in search pattern.

You can use double quotes in sed command. Also use & in replacement to avoid repeating matched text again.

sed "s/glob\.glob('\*\.txt')/&+glob.glob('*.dat')/" test.py

#!/usr/bin/env python

import os
import glob

for f in glob.glob('*.txt')+glob.glob('*.dat'):
    print f
anubhava
  • 761,203
  • 64
  • 569
  • 643