FreeKB - Perl (Scripting) Replace text in a file (-pi -e =~)
Perl (Scripting) - Replace text in a file (-pi -e =~)

Let's say foo.txt contains Hello World.

Hello World


There are two ways in which Perl can replace Hello World with some other value. One way is to use Perl on the command line and the other is withing a Perl script.

Command Line

In this example, the text "Hello" will be replaced with the text "Hi". It is also important to recognize that when the -i options is not used, the text in the file will not be changed. Instead, the result will simply be displayed in the terminal. 

perl -p -e 's/Hello/Hi/' foo.txt


The -i  option will actually change the content of the file.

perl -pi -e 's/Hello/Hi/' foo.txt



Let's say the $foo variable contains a value of Hello World.

my $foo = "Hello World";


Within a Perl script, the =~ operator is used to replace data. In this example, the $foo variable is updated so that "Hello" will be replaced with the "Hi".

$foo =~ 's/Hello/Hi/'



Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter 0fc7e in the box below so that we can be sure you are a human.


Web design by yours truely - me, myself, and I   |   |