Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!
I am trying to change parts of the file using something like the code here showing, is that a way to do it like this?
use stric; use warnings; my @files = qw( XY201308.TXT TW201308.TXT KG201308.TXT MM201308.TXT ); foreach my $file (@files) { # triyng to lower case the to letters and replace the digits with yy $file=~s/(\w{2})(\d+)/$1\lc($1),$2\lc(yy)/e; print "\n $file \n"; }
Thanks for looking!

Replies are listed 'Best First'.
Re: RegEx match in files
by choroba (Cardinal) on Aug 07, 2013 at 13:37 UTC
    Your code does not compile: strict ends in a "t".

    If you are using the /e option of the substitution, make sure the string is a valid Perl expression:

    $file =~ s/(\w{2})(\d+)/$1 . lc($1) . $2 . lc("yy")/e;

    Update: If you do not want to use the numbers, do not capture (and output) them:

    $file =~ s/(\w{2})\d+/$1 . lc($1) . "yy"/e;

    Note that you can use the \L special character instead of the lc function, which means you do not need the /e option at all:

    $file =~ s/(\w{2})\d+/\L$1yy/;
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: RegEx match in files
by rjt (Curate) on Aug 07, 2013 at 13:44 UTC
    triyng to lower case the to letters and replace the digits with yy

    It would help if you'd include a sample of the desired output, rather than just a description and sample code. However, if I understand you correctly, this will do:

        $file =~ s/^(\w\w)\d+/\L$1yy/;

    Outputs:

    xyyy.TXT twyy.TXT kgyy.TXT mmyy.TXT

    If you need the entire filename in lowercase, I might use another statement for clarity:

    $file =~ s/\d+/yy/; $file = lc $file;
    use strict; use warnings; omitted for brevity.
Re: RegEx match in files
by Laurent_R (Canon) on Aug 07, 2013 at 17:34 UTC

    This is unclear to me. You are saying that you want to modify some files, but your code (if it were to compile) would only try to modify the file names. What are you really trying to do?

    If you just want to rename your files, you could also try a Perl one-liner like this one:

     perl -e '$c=$_=shift; s/\d/yy/g; $d = lc ; rename $c, $d;' FOOBAR*.TXT

    Or, if you want to make sure you don't override an existing file (it might happen on some OS's, not quite sure):

     perl -e '$c=$_=shift; s/\d/yy/g; $d = lc ; rename $c, $d unless -e $d;' FOOBAR*.TXT