Showing posts with label find and replace. Show all posts
Showing posts with label find and replace. Show all posts

Friday, October 26, 2007

Unix Command to Find And Replace Text in a File

The following is a very simple, one-line command for finding and replacing all instances of a text pattern in a file (or files). There are numerous sources for this short script. It may seem completely trivial, but it comes in handy.
  • perl -pi -e 's/<find>/<replace>/' FILE_1 FILE_2 ... FILE_n

This will only replace the first occurrence of the pattern per line. If you want to replace all occurrences in every line, then add the 'g' option, like this.
  • perl -pi -e 's/<find>/<replace>/g' FILE_1 FILE_2 ... FILE_n

If you want the find to be case-insensitive, then use the 'i' option, like this.
  • perl -pi -e 's/<find>/<replace>/i' FILE_1 FILE_2 ... FILE_n

If you find that you need to replace file path names in text, then instead of back-slashing all the path separators in your pattern, you might want to choose a different s/// separator. I have found that '~' works pretty well (but if your paths contain '~'s, then you should experiment).
  • perl -pi -e 's~/path/to/my/file~/new/path/to/file~' FILE_1 FILE_2 ... FILE_n

If you want to replace some text with the contents of an environment variable, then you can access the environment with the hash ENV.

  • perl -pi -e 's~some_text~$ENV{environment_variable}~' FILE_1 FILE_2 ... FILE_n