0

Recursive search and replace with PCRE

Features

  • open source
  • command line tool
  • recursive search and replace in text files.
  • supports PCRE like Python does.
  • Installable via RPM/DPKG Ubuntu 14.04 without adding an extra package repo.
  • support for interactive search+replace.
  • Scripting solutions using sed, awk, ... are no solutions in my eyes.
1

You have answered your own question - just use python with re, fileinput & possibly even os.walk:

  • open source command line tool recursive search and replace in text files. Yes
  • supports PCRE like Python does. Yes exactly like python!
  • Installable via RPM/DPKG Yes If you don't have it already
  • Ubuntu 14.04 without adding an extra package repo. Yes
  • support for interactive search+replace. A python script can prompt the user for missing fields.
  • Scripting solutions using sed, awk, ... are no solutions in my eyes

A starting point:

import fileinput
import re

for line in fileinput.input(inplace=1, backup='.bak'):
    line = re.sub('foo','bar', line.rstrip())
    print(line)

this can even be done directly from the command line with:

python -c "import re, fileinput;for line in fileinput.input(inplace=1, backup='.bak'):; line = re.sub('foo','bar', line.rstrip()); print(line);" list_of_files

but you probably don't wish to type all of that every time. So something like:

#!/usr/bin/env python
"""
wcreplace Find and replace wildcards on input files

Usage:
wcreplace findwc replacewc file...
"""
import sys
import fileinput
import re

if len(sys.argv) < 4:
    print("ERROR: Not enough parameters")
    print(__doc__)
    sys.exit(1)

findwc = sys.argv[1]
replacewc = sys.argv[2]

for line in fileinput.input(sys.agv[3:], inplace=1, backup='.bak'):
    line = re.sub(findwc, replacewc, line.rstrip())
    print(line)

Put in a file called wcreplace, somewhere on the path like /usr/bin and set to executable with chmod 755 wcreplace should do the job.

Note: The above is untested! so test before use!

3
  • Yes, this works, even on one line. Is there not solution which just takes my regex- and insert-string? I could write a python script. I know, but I would like to have something which can be installed via RPM/DPKG.
    – guettli
    May 31 '16 at 19:53
  • @guettli - added a rough and ready script. May 31 '16 at 20:21
  • Yes this works. I wrote such a script some time ago: github.com/guettli/reprec but I would like to have something which is already available as RPM/DPKG. I just can't believe that modern linux distributions don't contain such a tool. It this is the case, then I will package my version (what tried to avoid).
    – guettli
    Jun 1 '16 at 10:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.