How To Replace A Text Exists In Many Files?
Linux provides a lot of tools to ease system administrators work. One of them is replace command which simple search text files to replace string and create new text file. Replace command comes with MySQL Server packages. IF MySQL is not installed we can not use replace command.
We can use replace command to change string in text files.
$ replace BEFORE AFTER < YOURCOMMAND > NEWTEXTFILE
- replace is our tool
- BEFORE is the string we search for
- AFTER is the new string
- < YOURCOMMAND is our original text file
- > NEWTEXTFILEis newly created text file with replaces string
Beginning and End Of File
We can specify beginning and end of file with ^ $
$ replace ^Before After < yourcommand > newtextfile
- Replace string Before which is in the beginning of the line
Alternative to replace command is sed. Sed is generally installed by default most of the distributions. So we can replace sed with replace 🙂
$ sed 's/Before/After/g' < yourcommand.txt > newtextfile
$ sed 's/Before//After/g' yourcommand.txt
In this example replace done in place so new file wouldn’t created
Perl Old Friend
We can accomplish replacement with Perl just like below
perl -p -i -e 's/Before/After/g' yourcommand.txt