Do something for lines that do or do not END with a certain pattern in Perl

Home > Search
  by

Append to end of line

The $ character is used to do something from the end of a line. For example, let's say file.txt contains the text "Hello World". $ can be used to append to the end of the string. In this example, "Testing" is appended to the end of "Hello World".

$file = "/path/to/file.txt";
open(FH, '>>', $file) or die "cannot open $file";

while (<FH>) {
  $_ =~ s|$|Testing|;
}

close(FH);

 


Replace end of line

The $ character is often used to replace text at the end of a line. In this example, lines ending with the word "World" are replaced with the word "Earth".

$file = "/path/to/file.txt";
open(FH, '>>', $file) or die "cannot open $file";

while (<FH>) {
  $_ =~ s|World$|Earth|;
}

close(FH);

 



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.




Comments