Setup a Linux Server

Setup a Linux Server

Replace a single string in a large number of files in Unix

If you have Perl installed on your system

With Perl, you can make the replacement from the Unix command line prompt. At the prompt, enter:

 perl -pi -e 's/old_string/new_string/g' file_pattern

Replace old_string with the string you want to replace and new_string with the replacement string. Replace file_pattern with the files you want to modify. This can be a shell wildcard, such as *.html. The search is case sensitive and Perl will replace substrings of words. For example, take the following command:

 perl -pi -e 's/temp/tmp/g' *.html

Perl would change every instance of temp it found into tmp (including instances of temporary; it would change them to tmporary because of the temp string in the beginning of the word), but would not change the word TEMP into tmp. If the string has characters Perl or the shell would normally interpret as commands, such as / (a forward slash), < (a less-than symbol), > (a greater-than symbol), or ; (a semicolon), put \ (a backslash) before the character. Take the following replacement string, for example:


To correctly replace it, you would have to escape the forward slashes with the escape character (the backslash) so that the forward slashes aren’t interpreted as commands. Your replacement string would need to be:

Replace a single string in a large number of files in Unix

Leave a Reply

Scroll to top