I am trying to write a script which takes a file as input, reads each line of that file, performs a find based on the value of the file contents, and writes the output to a different file. What I have so far does not do anything.

I'm not concerned about making the code look pretty or adhering to good programming rules right now. The script will be used once to traverse several hundred lines of input file and never used again.

$in_file = $ARGV[1];
$out_file = '<my_output>.out';

open(IN, "< $in_file");

    print "input  $in_file \n";
 find /<directory> -type f -name $_ -print >> $out_file;
  • Are you saying that you have a file "thelist" with a list of filenames, and for each file in "thelist", you want to run "find"? If so, then it sounds as though you want to use xargs, e.g.: xargs -n 1 find [...] < thelist – arensb Jan 6 '17 at 17:14
  • 1
    So far it looks like this could be done in pure Bash, which will be simpler. Is it important to use Perl? – janos Jan 6 '17 at 17:30
  • You need to use backticks or system() to execute external commands. See perldoc.perl.org/perlop.html#Quote-Like-Operators and perldoc.perl.org/functions/system.html – glenn jackman Jan 6 '17 at 17:42
#!/usr/bin/env perl
use strict;
use warnings;
use Getopt::Long qw(GetOptions);

GetOptions( 'dir=s' => \my $Flag_Directory ) or exit 1;

die "Usage: $0 [--dir=d] inputfile outputfile\n" if @ARGV < 2;

$Flag_Directory = '/etc/' if !defined $Flag_Directory;
$Flag_Directory = quotemeta($Flag_Directory);

my $output_file = pop @ARGV;
open my $outfh, '>', $output_file
  or die "$0: could not write '$output_file': $!\n";

while (readline) {
    print "input: '$_'\n";
    my $filename = quotemeta($_);
    print $outfh qx(find $Flag_Directory -type f -name $filename -print);

Though in Perl it would be more idiomatic to instead use File::Find or File::Find::Rule instead of shelling out.

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.