#!/usr/bin/perl use warnings; use strict; open my $fh, '<', 'hii.txt' or die "Can't open the damn file for reading!: $!"; my @file_content; while ( my $line = <$fh> ){ chomp $line; if ( $line =~ /\s+.* one Link Start$/){ next unless($line=~/\s+.*second Link Start\s*--%>$/); $line =~ s/\s+--%>//; s/\s+.* one Link Start$/\s+.* one Link Start\s*--%>/gi; } elsif ($line =~ /\s+.* second Link Start$/){ next unless($line=~/\s+.*oneLink Start\s*--%>$/); $line =~ s/\s+--%>//; s/\s+.* second Link Start$/\s+.* second Link Start\s*--%>/gi; } } close $fh; print $line; open(my $output_fh, '>', 'hii.txt') or die "Unable to open file for writing: $!"; print $output_fh $line; close $output_fh;