LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   pattern match anything before "dot" (https://www.linuxquestions.org/questions/linux-newbie-8/pattern-match-anything-before-dot-697546/)

ufmale 01-15-2009 12:01 PM

pattern match anything before "dot"
 
I want to replace the filename name.exe with --FILE--.exe as part of my perl script.
Is there an easy way to do that with pattern matching?
Bascially, i want to match anything before ".exe", then replace them with "--FILE--".

mk27 01-15-2009 12:33 PM

use =~// to match
use =~s/// to substitute:
Code:

#!/usr/bin/perl -w
use strict;

while (<DATA>) {
        chomp $_;        # remove newline
        if ($_=~/\.exe$/) {        # check if input ends with .exe
                $_=~s/^\w+/--FILE--/;  # replace alphanumeric content at beginning
        }
        print "$_\n";
}

__DATA__
file.exe
this.exe
notthis.txt
more.exe

Output:
--FILE--.exe
--FILE--.exe
notthis.txt
--FILE--.exe


\w is an alphanumeric character
+ is one or more of the character
\. is a real period (. is anything)
^ indicates the beginning
$ indicates the end

Google "Rex Swain's HTMLified Perl 5 Reference Guide"; it's a great, very short quick reference that includes all the regular expression stuff.

Also perlmonks.com is a very active and helpful forum :)

TB0ne 01-15-2009 12:35 PM

Quote:

Originally Posted by ufmale (Post 3410030)
I want to replace the filename name.exe with --FILE--.exe as part of my perl script.
Is there an easy way to do that with pattern matching?
Bascially, i want to match anything before ".exe", then replace them with "--FILE--".

You can use sed to do this, if you want ALL the files to be "--FILE--.exe".


$variable =~ s/<variable where your input comes from>/"--FILE--.exe"/;

Check the syntax, though...not sure that's right. :)


All times are GMT -5. The time now is 10:55 AM.