簡體   English   中英

Perl 腳本,將 linux 路徑作為用戶輸入直到一個目錄,需要獲取所有具有通用名稱的目錄的 output

[英]Perl script that takes linux path as input from the user till a directory and need to get the output of all the directories with common name

我已經編寫了 Perl 腳本,該腳本將 linux 路徑作為用戶的輸入,直到某個目錄並打印其中具有通用名稱的所有目錄,例如,如果用戶輸入是/user/images/mobile_photos/mobile_photos我有一個列表以image_開頭的目錄,例如image_user_1,image_user_2,...,image_user_10並且在每個目錄中都有圖像質量,例如best,good,bad作為文件quality.txt中的字符串。 現在我需要在一個文件中獲取這些目錄的列表,其中包含目錄名稱旁邊的圖像質量。

一個例子的實際路徑

/user/images/mobile_photos/image_user_1/quality.txt

用戶應輸入為

/user/images/mobile_photos/

temp.txt中所需的 output 是

image_user_1 good
image_user_2 bad
image_user_3 best
image_user_4 best 
.
.
.
image_user_10 bad

以下是僅用於圖像質量良好的代碼

#! /usr/bin/perl
 use strict;
 use warnings;
 my $path = <STDIN>;
 my $dir = system ("ls -d $path/image_*/quality.txt "good" > temp.txt");
 print "$dir";
 exit(0);

但是我將終端 output 作為/user/images/mobile_photos/並且temp.txt為空。

沒有理由為此向system輸出 go。 那樣只會復雜得多,而且還有一個額外的挑戰是讓所有的引號和轉義符都正確

use warnings;
use strict;
use feature 'say';

use File::Glob ':bsd_glob';

my $path = shift // die "Usage: $0 path\n";

my @qual_files = glob "$path/image_*/quality.txt"

say for @qual_files;  # just to see them

# Save list to file
my $out_file = 'temp.txt';
open my $fh_out, '>', $out_file or die "Can't open $out_file: $!";
say $fh_out $_ for @qual_files;
close $fh_out or warn "Error closing $out_file: $!";

內置glob具有一組有限的類似於 shell 的元字符。 我使用File::Glob因為它可以很好地處理文件名中的空格等問題。

當然還有其他方法可以讀取目錄和 select 條目。


請解釋如何決定問題要求與文件名一起寫入的“好”與“壞”(等)詞。

使用低級opendirreaddir

#! /usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

chomp( my $path = <STDIN> );
opendir my $dir, $path or die "Can't open $path: $!";
while (my $dir = readdir $dir) {
    next unless -d "$path/$dir" && $dir =~ /^image_/;

    if (-f "$path/$dir/quality.txt") {
        open my $q, '<', "$path/$dir/quality.txt"
            or die "Can't open $dir/quality.txt: $!";
        chomp( my $quality = <$q> );
        say "$dir\t$quality";
    } else {
        warn "quality.txt not found in $dir.\n";
    }
}

或者使用Path::Tiny (強烈推薦:):

#! /usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

use Path::Tiny qw{ path };

chomp( my $path = <STDIN> );
$path = path($path);
die "Not a directory\n" unless $path->is_dir;

for my $dir ($path->children(qr/^image_/)) {
    next unless $dir->is_dir;

    my $quality_file = $dir->child('quality.txt');
    if ($quality_file->is_file) {
        chomp( my $quality = $quality_file->slurp );
        say "$dir\t$quality";
    } else {
        warn "quality.txt not found in $dir.\n";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM