How to replace text in Perl (sed)

Home > Search > How-to

Replace text in variable

Following is a very basic example of how to replace text in a variable in Perl. In this example, the $original variable first contains the text "Hello World". Then, the word "World" is replaced with "Earth". Printing $original will display "Hello Earth".

$original = "Hello World";
$original =~ s/World/Earth/g;
print $original;


Create new variable

Sometimes, you'll want to create a new variable that contains the replaced text. In this example, a new variable named $new is created. In this example, the $original variable will have "Hello World" and the $new variable will have "Hello Earth".

$original = "Hello World";
($new = $original) =~ s/World/Earth/g;
print $original;
print $new;


Replace multiple strings

Usually, multiple strings are replaced by listing multple replacement commands. In this example, the world "Hello" is replaced with "Goodbye" and then the world "World" is replaced with "Earth". In this example, $original will have "Hello World" and $new will have "Goodbye Earth".

$original = "Hello World";
$new = $original;

$new =~ s/Hello/Goodbye/;
$new =~ s/World/Earth/;

print $original;
print $new;


Replace text in a file

Let's say file1.txt contains "Hello World", and you want to redirect the content of file1.txt to file2.txt, and elimiate the word "Hello".

open(IN, '<', '/path/to/file1.txt') or die "cannot open file";
open(OUT, '>>', '/path/to/file2.txt') or die "cannot open file";

  $_ =~ s/Hello//g;
  print OUT $_;



Let's say file.txt contains the text "Hello World". The following Perl script will open file.txt, and then replace the text "World" with "Earth".

open(FH, '<', '/path/to/file.txt') or die "cannot open file";
my @lines = <FH>;

my @newlines;
foreach(@lines) {
  $_ =~ s/World/Earth/g;

open(FH, '>', '/path/to/file.txt') or die "cannot open file";
print FH @newlines;



Let's say you have an array.

my @fruits = qw(apple banana orange grapes);


The map function can be used to do a replacement on the array. In this example, the text "orange" is replaced with "pinneapple".

map { s/orange/pinnapple/g } @fruits;


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 in the box below so that we can be sure you are a human.