Replacing text in multiple files

From Helpful
Revision as of 14:29, 17 February 2010 by Helpful (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
These are primarily notes
It won't be complete in any sense.
It exists to contain fragments of useful information.

You can get string/regexp subsitution in multiple files (think code, or replacing incorrect word usage) using a few different commands

using sed

sed -i.bak 's/\bgetSession\b/get_session/g' *.cpp

The \b (test for word border) in this example avoids potentially nasty substring replaces.

The .bak argument to -i makes sed make a backup (with that extension), just in case you want to restore the old copy/copies. If you're happy (you could diff the two to check the changes) you can remove these backups.


Note you can be useful to use alternative delimiters if you need them to avoid (some) confusion, e.g.

sed -i.bak 's_[^/]common.css_css/common.css_g' *.html

(See also sed)

using perl

perl -pie 's/\bgetSession\b/get_session/g' *.cpp

Where:

  • -p: loop
  • -i: edit in-place
  • -e: "execute the following"

using replace

Written by/for MySQL, and installed only as part of it.

No regexps or guards like \b for matching words or code symbols neatly (other than
" adjacent spaces "
)

You can give multiple replacements, for example:

replace getSession get_session " cake " " pie " -- *.txt

Replacements are independent of each other, so you can swap, for example 'cake' with 'pie':

replace " cake " " pie " " pie " " cake " -- *.txt