Replacing text in multiple files

From Helpful
Jump to navigation Jump to search

📃 These are primarily notes, intended to be a collection of useful fragments, that will probably never be complete in any sense.

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


using perl

Perhaps easiest to remember as a command.

perl -p -i -e 's/\bgetSession\b/get_session/g' *.cpp

Where:

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

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 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