Replacing text in multiple files: Difference between revisions

From Helpful
Jump to navigation Jump to search
mNo edit summary
Line 7: Line 7:
Perhaps easiest to remember as a command.
Perhaps easiest to remember as a command.


<code lang="bash">
<syntaxhighlight lang="bash">
perl -p -i -e 's/\bgetSession\b/get_session/g' *.cpp
perl -p -i -e 's/\bgetSession\b/get_session/g' *.cpp
</code>
</syntaxhighlight >
Where:  
Where:  
* -p: loop
* -p: loop
Line 19: Line 19:


=using <tt>sed</tt>=
=using <tt>sed</tt>=
<code lang="bash">
<syntaxhighlight lang="bash">
sed -i.bak 's/\bgetSession\b/get_session/g' *.cpp
sed -i.bak 's/\bgetSession\b/get_session/g' *.cpp
</code>
</syntaxhighlight >
The <tt>\b</tt> (test for word border) in this example avoids potentially nasty substring replaces.
The <tt>\b</tt> (test for word border) in this example avoids potentially nasty substring replaces.


Line 28: Line 28:


Note you can be useful to use alternative delimiters if you need them to avoid (some) confusion, e.g.  
Note you can be useful to use alternative delimiters if you need them to avoid (some) confusion, e.g.  
<code lang="bash">
<syntaxhighlight lang="bash">
sed -i.bak 's_[^/]common.css_css/common.css_g' *.html
sed -i.bak 's_[^/]common.css_css/common.css_g' *.html
</code>
</syntaxhighlight >


(See also [[sed]])
(See also [[sed]])

Revision as of 13:17, 23 July 2023

📃 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