in reply to Check if file exists in multiple directories

At a first glance, your logic says if in the directory there is a .txt file, then move a file called "outFile" to the directory. Is that what you want?

  • Comment on Re: Check if file exists in multiple directories

Replies are listed 'Best First'.
Re^2: Check if file exists in multiple directories
by Bama_Perl (Acolyte) on May 21, 2015 at 18:01 UTC
    Yes if there is a .txt file, move the file called outFile to the new directory. Correct.

      Hi Bama_Perl,

      What I don't understand is do you want the file "outFile" moved or copied? Because, if you move it to say the first directory that has '*.txt', what happens to another say "fourth" directory that also has '*.txt'?

      Secondly, I think you should be using a perl core module like File::Copy to achieve your aim instead of using mv command in system like you are doing.

      Third, you may use File::Find module to do the searching of directories for you.
      Lastly, use three arguments open function and a lexical scoped file-handler (this is an old wisdom that still holds true in a way today)

      If you tell me, I'll forget.
      If you show me, I'll remember.
      if you involve me, I'll understand.
      --- Author unknown to me
        Hi 2teez, I want to copy the $outFile to a new directory. I don't want to move it to a directory that has *.txt. In other words, as I loop through each directory, if that directory has a *.txt file, then I want to move the $outfile within that directory to a new directory. If that directory does not have a *.txt file, then nothing will be moved to a new directory. I'll look into File::Copy to see how that can help me. Thanks!

      Your $dir probably has an extra newline at the end, try chomp @tablea; after reading the dirlist file.

        #!/usr/bin/perl use warnings; use Cwd; $out = "outFile"; $newdir = $newdirectory; open(TABLEA, "dirlist"); @tablea = <TABLEA>; foreach $dir (@tablea) { chomp @tablea; chdir $dir; print(cwd); print "\n"; if (glob("*.txt")) { system("mv $out $newdir"); } }
        If I add the chomp and I print the current working directory, the only directory that gets printed is the first directory, multiple times(as many times there are files in the main directory). Any other thoughts? Thanks.