In my /var/tmp I have the following files:

 ls | grep FILE

With the following command I cut the first word of the files as follows:

ls /var/tmp | grep FILE.xml | sed "s/.FILE.*//"

I get:


How can I do the same thing with Perl in order to insert the "AAA" and "BBB" in to @RESULTS? For example:

@RESULTS=perl syntax ...
  • 1
    UUOG: sed -n "/FILE.xml/s/.FILE.*//p" – Ignacio Vazquez-Abrams Jul 15 '10 at 11:01
  • its not perl please see b0fh answer – yael Jul 15 '10 at 11:15
  • 1
    And that's why it's not an answer. – Ignacio Vazquez-Abrams Jul 15 '10 at 11:30

Assuming you want to keep using the existing command, you could do

my @results = `ls /var/tmp | grep FILE.xml | sed "s/.FILE.*//"`;
chomp for @results;

the chomp is to get rid of the trailing newline.

Without resorting to calling external commands:

my @results;
opendir DIR,"/var/tmp" or die "Cannot open dir: $!";
for (readdir DIR) {
    /(.*)-FILE.*/ or next;
    push @results, $1;
closedir DIR;
  • THX very good I choose the second option in my perl script – yael Jul 15 '10 at 10:48
  • something else how to change your syntax in case the "-" not appears for example from AAA1FILE.xml it will return AAA1 – yael Jul 15 '10 at 11:07
  • You can replace that ls|grep|sed with sed -ne's/.FILE.*//p' /var/tmp – Evan Carroll Jul 29 '10 at 16:01

@RESULTS = grep(s[/var/tmp/(.*)-FILE.xml][$1],</var/tmp/*>);

@RESULTS = map /(.*)-FILE\.xml$/, <*-FILE.xml>;
@RESULTS = map m#/var/tmp/(.*)-FILE.xml#, </var/tmp/*-FILE.xml>;
perl -nE'next unless s/-FILE.*//; push state @lines, $_; die @lines if eof;' /var/tmp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.