Differences between revisions 49 and 50
Revision 49 as of 2012-07-18 09:18:57
Size: 1770
Editor: Lhunath
Comment: Axe the noise. Nobody reading this FAQ cares about that.
Revision 50 as of 2012-07-18 09:20:05
Size: 1770
Editor: Lhunath
Comment:
Deletions are marked like this. Additions are marked like this.
Line 7: Line 7:
'''Warning''': A lot of bad advice on the Internet will recommend `sed -i` or `perl -e` for this. While on the surface it may look like these tools modify your files, what they ''really'' do is recreate your file and delete the original. This has many downsides and is often very risky. Open handles are destroyed, certain metadata will get lost, a lot of excess disk I/O is involved, and depending on the implementation, interrupted operations may cause your file to get lost. Just use a file editor. '''Warning''': A lot of bad advice on the Internet will recommend `sed -i` or `perl -i` for this. While on the surface it may look like these tools modify your files, what they ''really'' do is recreate your file and delete the original. This has many downsides and is often very risky. Open handles are destroyed, certain metadata will get lost, a lot of excess disk I/O is involved, and depending on the implementation, interrupted operations may cause your file to get lost. Just use a file editor.

How can I replace a string with another string in a file?

We're trying to edit files, which means we need a file editor. Most systems come with a range of editors, but POSIX defines only two that we can use: ed and ex.

Warning: A lot of bad advice on the Internet will recommend sed -i or perl -i for this. While on the surface it may look like these tools modify your files, what they really do is recreate your file and delete the original. This has many downsides and is often very risky. Open handles are destroyed, certain metadata will get lost, a lot of excess disk I/O is involved, and depending on the implementation, interrupted operations may cause your file to get lost. Just use a file editor.

ed is the standard UNIX command-based editor. ex is another POSIX command-based editor with syntax slightly similar to that of sed. Here are some commonly-used syntaxes for replacing the string old by the string new in a file named file.

ex -sc '%s/old/new/ge|x' file
ed -s file <<< $'g/old/s//new/g\nw\nq'

If you need to edit multiple files, ex can easily be combined with find. ed is hard to call from find since it takes commands as input.

find . -type f -exec ex -sc '%s/old/new/ge|x' {} \;
find . -type f -exec bash -c 'printf "%s\n" "g/old/s//new/g" w q | ed -s "$1"' _ {} \;

You may notice that this causes an ex/ed process per file. If your ex is provided by vim (NOT POSIX), you can optimize that into:

find . -type f -exec ex -sc 'argdo %s/old/new/ge|x' {} +

This will run a single ex for as many files as fit on the command line. You can't do this with ed.


CategoryShell

BashFAQ/021 (last edited 2022-11-03 23:42:27 by GreyCat)