Bash Shell: Replace a String With Another String In All Files Using sed and Perl -pie Options

Bash Shell: Replace a String With Another String In All Files Using sed and Perl -pie Options

To replace a string with another string in all files in a directory, you can use the sed command with the -i (in-place edit) option and the -e (expression) option. The -i option allows you to edit the files in place, replacing the original files with the modified versions, while the -e option allows you to specify a sed expression to apply to the input.

For example, to replace the string oldstring with the string newstring in all the .txt files in the current directory, you can use the following command:

sed -i -e 's/oldstring/newstring/g' *.txt
Source:w‮ual.ww‬tturi.com

This will modify all the .txt files in the current directory, replacing oldstring with newstring in each file. The g flag at the end of the sed expression indicates that the replacement should be performed globally, replacing all occurrences of oldstring in each file.

Alternatively, you can use the perl command with the -pi (in-place edit) option to achieve the same result. For example:

perl -pi -e 's/oldstring/newstring/g' *.txt

This will also replace oldstring with newstring in all the .txt files in the current directory.

It is important to be careful when using these commands, as they can modify multiple files at once, and there is no way to undo the changes. It is always a good idea to test the commands with a small number of files before running them on a large number of files to ensure that they are working as expected.

For more information about the sed and perl commands and their options, you can consult the documentation for your specific Unix or Linux system.

Created Time:2017-10-27 14:56:35  Author:lautturi