foreach my $line (<>) { chomp ($line); if ($line =~ m/^>/) { #if line matches ">" at beginning if ($line =~ /\s/g) { #if line matches whitespace globally $line =~ s/\]/\s/; $line =~ s/\[/\s/; $line =~ s/\s /_/g; #substitute whitespace with underscore. } } }