$ perl -le ' > $str = qq{Keyword string\nBlah\nKeyword\nstring\nBlech\nKeyword "string"}; > print $str; > print; > $str =~ s{Keyword(\s+"?)string}{Keyword${1}1_string}sg; > print $str;' Keyword string Blah Keyword string Blech Keyword "string" Keyword 1_string Blah Keyword 1_string Blech Keyword "1_string" $