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

Dear ALL, In my folder:
ls -ltr TRC_20160309_1.ARC TRC_20160309_1.PDF TRC_20160308_1.PDF
if the search pattern is found in TRC_20160309_1.ARC.  grep -l 'TCO' *.ARC I want to move both TRC_20160309_1.ARC and TRC_20160309_1.PDF since the name is similar. I know perl can do this but am really lost. Thanks in advance.

Replies are listed 'Best First'.
Re: perl file processing
by Laurent_R (Canon) on Mar 10, 2016 at 22:04 UTC
    What do you mean "to move both TRC_20160309_1.ARC and TRC_20160309_1.PDF since the name is similar"? Move to a different folder? Something else? Please try to bemore specific.
Re: perl file processing
by FreeBeerReekingMonk (Deacon) on Mar 10, 2016 at 22:13 UTC
    Start with creating loops: readdir

    Once you have the ARC files, just open, read them and grep on your criteria open

    Then, move the file by renaming it (basically, you change the directory) rename

    Why not in shell?

    for ARC in `grep -l 'TCO' *.ARC`; do PDF=`basename -s ARC "$ARC"`PDF; if [ -f "$PDF" ]; then echo "Both $ARC and $PDF exist, do the move"; fi; done

      I just tried that on my windows computer and it didn't work at all 8-D

      A nice thing about Perl is that to a large extent ash/bash/csh/dash/ksh/.../zsh type activities written in Perl have a much better chance of working across systems.

      Update: Zoidberg may give the best of both worlds of course.

      Premature optimization is the root of all job security
Re: perl file processing
by Marshall (Canon) on Mar 14, 2016 at 00:45 UTC
    When processing the filenames, create a hash of array. Each "basename" like TRC_20160309_1 will have an array of extensions associated with it. You did great with test cases, I added a couple more.

    You can feed your ls command into this, change <DATA> to just <> in order to read stdin. perl thisprog <yourLScommand

    #usr/bin/perl use strict; use warnings; my %fileBaseNames; while (my $fullName = <DATA>) { next if ($fullName =~ /^s*$/); #skip blank lines #separate the full name into name and extension my ($name, $ext) = ($fullName =~ /(\w+)\.(\w+)/); push( @{ $fileBaseNames {$name} }, $ext); } # Each hash key of %fileBaseNames contains an array of the # .extensions found for that name foreach my $baseName (sort keys %fileBaseNames) { my (@extensions) = @{$fileBaseNames{$baseName}}; print "file $baseName has the extensions: @extensions\n"; #code to use that for selective copy goes here... } =EXAMPLE printout file TRC_20160308_1 has the extensions: PDF PL file TRC_20160309_1 has the extensions: ARC PDF ADF file TRC_20160310_1 has the extensions: PDF Process completed successfully =cut __DATA__ TRC_20160309_1.ARC TRC_20160309_1.PDF TRC_20160309_1.ADF TRC_20160308_1.PDF TRC_20160308_1.PL TRC_20160310_1.PDF