#!/usr/bin/perl -w use strict; use warnings; my $line = 0; my $file_name = "test.txt"; open(my $fh, '<', $file_name) || die "file could not open $! \n"; while( $line = <$fh>) { if( $line =~ s/\btest\b/^\#/ig ) { print "$line\n"; } } close($fh);