使用 perl 脚本在目录中查找文件

HelpMeAndroidStudio

我正在尝试开发一个 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 上传它。剩下的就完成了,只是它可以自动定位文件的部分

林·杜拉特

尽管在 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");

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用文件统计信息在perl中查找文件的模式

使用vb 6.0在目录中查找文件

使用Shell脚本查找文件

查找文件并使用Shell脚本打包

使用Java 8在目录和子目录中查找文件

如何仅在给定目录中查找文件,并使用bash忽略子目录

使用Glob在目录中查找文件会使文件形成错误的文件夹

如何使用sed(或awk或perl单行代码)从文件A中的特定列获取值,并使用它来查找文件B中的行?

使用Perl程序在文件中查找文本

如何使用 bash 脚本在文件内容中查找文件名?

在Perl中查找文件-拒绝跳过权限

如何使用其ID在一组目录中查找文件

如何使用find在指定子目录中查找文件

如何使用regexp在Python目录中查找文件名

使用grep查找文件中的负数

使用Bash脚本查找文件中字符串的行号

使用bash脚本查找文件中的最小数目

使用 shell 脚本在字符串中查找文件扩展名

仅在特定目录中使用 find 命令查找文件,即使该文件存在于其他目录中

如何使用XP cmd目录查找文件?

如何使用特定的ACL查找文件/目录

使用os.expanduser(python)后查找文件目录

如何使用python遍历路径并查找文件和目录?

如何在特定目录中按文件扩展名查找文件并使用Power Shell进行遍历?

在 Perl 中使用多个输出文件在多个目录中运行脚本(比较哈希键值的问题)

使用命名参数在perl脚本中运行perl脚本

使用未知的perl位置运行perl脚本

使用Perl查找并修复CSV文件中的错误

使用反引号获取 perl 脚本中的核心文件