How Do I Replace A Text String In Many Files At Once?

The replace command is a string-replacement utility. It changes strings in place in files or on the standard input. This command uses a finite state machine to match longer strings first. It can be used to swap strings. This command is similar to the Perl -pie syntax or sed (stream editor) command.

Please note that the replace command is part of is MySQL database system. If you don’t have MySQL installed, you donÒ€ℒt have replace command.

Advertisement

Syntax

replace OLD-STRING NEW-STRING < INPUT-FILE > OUTPUT-FILE

Examples

To replace all occurrences of word UNIX with Linux, enter:
$ replace UNIX Linux < oldfile > newfile

The replace command can be used in a pipeline, run:
$ cat /etc/passwd | replace : '|'

You can skip the cat command, enter:
$ replace : '|' < /etc/passwd

It also supports few special characters in string replacement:

  • \^ : Match start of line.
  • $ : Match end of line.

How Do I Update All *.txt Files At Once?

You use bash for loop as follows:

#!/bin/bash
for f in /path/to/*.txt
do
   replace UNIX Linux < "$f" > "$f.new"
done

The replace command does not understand regular expression. To use regular expression try the sed command or Perl.

Sed Command Example

To replace all occurrences of word UNIX with Linux using the sed command, enter:

sed 's/UNIX/Linux/g' < input.file > output.file

OR

sed -i 's/UNIX/Linux/g' input.file

OR use bash shell for loop as follows to update all *.doc files at once:

#!/bin/bash
for f in /path/to/*.doc
do
   sed -i  's/UNIX/Linux/g' "$f"
done

Updated for accuracy!

πŸ₯Ί Was this helpful? Please add a comment to show your appreciation or feedback.

nixCrat Tux Pixel Penguin
Hi! 🀠
I'm Vivek Gite, and I write about Linux, macOS, Unix, IT, programming, infosec, and open source. Subscribe to my RSS feed or email newsletter for updates.

21 comments… add one
  • asdds Jun 17, 2013 @ 13:11

    Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre> for code samples. Your comment will appear only after approval by the site admin.