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.
replace OLD-STRING NEW-STRING < INPUT-FILE > OUTPUT-FILE
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
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!