in reply to Replace only selected characters

You describe replacing only the first comma, but then expect exactly the opposite: "ABC,XYZ PERL IS AWESOME INNIT". It seems you want to remove all commas except for the first.

Try this. It "looks behind" for a comma, without consuming it; then matches (and stores) up to a comma; then replaces; and repeats.

s/(?<=,)([^,]*),/\1/g;

Replies are listed 'Best First'.
Re^2: Replace only selected characters
by rohanan (Novice) on Oct 14, 2011 at 18:58 UTC
    That worked!. Thanks for the solution. I learned something today :)
Re^2: Replace only selected characters
by rohanan (Novice) on Oct 14, 2011 at 21:41 UTC
    Hi, Im struggling to Use this against a csv file with several lines of lines like this which needs formatting.
    open(FILE, "<ABC.csv"); @lines = <FILE>; print @lines; print $lines[1]; close(FILE); foreach ($lines) { $lines = ~ s/(?<=,)([^,]*),/\1/g; print("$lines \n"); }
    what am I doing wrong now :(
      foreach ($lines) { $lines = ~ s/(?<=,)([^,]*),/\1/g; print("$lines \n"); }

      In addition to the fact that the scalar  $linesdoesn't appear to be defined anywhere (you are using warnings and strictures, aren't you?), the statement
          $lines = ~ s/(?<=,)([^,]*),/\1/g;
      should probably be
          $lines =~ s/(?<=,)([^,]*),/$1 /g;
      (the  =~ operator should have no space between = and ~, use  $1 instead of  \1 in the replacement string, there should actually be a space somewhere in the replacement string if you want to replace a ',' with a space). I would suggest something like (untested):

      foreach my $line (@lines) { $line =~ s/(?<=,)([^,]*),/$1 /g; print("$line \n"); }

      Update: After further inspection of the OP and replies, it appears that rohanan wants every ',' after the first replaced with the empty string rather than with a space. So (still untested):
          $line =~ s/(?<=,)([^,]*),/$1/g;

      Hi,

      'foreach ($lines) {' -
      should this be 'foreach (@lines) {' ?

      And so on

      J.C.