首页 > 解决方案 > 使用 perl 脚本在目录中查找文件

问题描述

我正在尝试开发一个 perl 脚本,该脚本在用户的所有目录中查找特定文件名,而无需用户指定文件的整个路径名。

例如,假设感兴趣的文件是data.list. 它位于/home/path/directory/project/userabc/data.list. 在命令行中,通常用户必须指定文件的路径名才能访问它,如下所示:

cd /home/path/directory/project/userabc/data.list

相反,我希望用户只需script.pl ABC在命令行中输入,然后 Perl 脚本将自动运行并检索其中的信息data.list.,在我的情况下,计算行数并使用 curl 上传。剩下的就完成了,只是可以自动定位文件的部分

标签: linuxperl

解决方案


尽管在 Perl 中非常可行,但这在 Bash 中看起来更合适:

#!/bin/bash

filename=$(find ~ -name "$1" )
wc -l "$filename"
curl .......

主要问题当然是如果您有多个文件data1,例如/home/user/dir1/data1/home/user/dir2/data1. 您将需要一种方法来处理它。你如何处理它取决于你的具体情况。

在 Perl 中会复杂得多:

#! /usr/bin/perl -w
    eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
        if 0; #$running_under_some_shell

use strict;

# Import the module File::Find, which will do all the real work
use File::Find ();

# Set the variable $File::Find::dont_use_nlink if you're using AFS,
# since AFS cheats.

# for the convenience of &wanted calls, including -eval statements:
# Here, we "import" specific variables from the File::Find module
# The purpose is to be able to just type '$name' instead of the
# complete '$File::Find::name'.
use vars qw/*name *dir *prune/;
*name   = *File::Find::name;
*dir    = *File::Find::dir;
*prune  = *File::Find::prune;

# We declare the sub here; the content of the sub will be created later.
sub wanted;

#  This is a simple way to get the first argument. There is no 
# checking on validity.
our $filename=$ARGV[0];


# Traverse desired filesystem. /home is the top-directory where we
# start our seach. The sub wanted will be executed for every file 
# we find
File::Find::find({wanted => \&wanted}, '/home');
exit;


sub wanted {
    # Check if the file is our desired filename
    if ( /^$filename\z/) {
        # Open the file, read it and count its lines
        my $lines=0;
        open(my $F,'<',$name) or die "Cannot open $name";
        while (<$F>){ $lines++; }
        print("$name: $lines\n");

        # Your curl command here
    }
}

您将需要查看参数解析,我只是使用它$ARGV[0],但我不知道您的 curl 是什么样的。

一种更简单(虽然不推荐)的方法是滥用 Perl 作为一种 shell:

#!/usr/bin/perl
#
my $fn=`find /home -name '$ARGV[0]'`;
chomp $fn;
my $wc=`wc -l '$fn'`;
print "$wc\n";
system ("your curl command");

推荐阅读