Thread Verzeichnis Struktur auslesen und in String oder Array speichern (12 answers)
Opened by gtrdriver at 2019-01-30 21:01

Linuxer
 2019-01-31 16:52
#189682 #189682
User since
2006-01-27
3870 Artikel
HausmeisterIn

user image
Schau mal, ob Du bei Dir das Programm "find2perl" verfügbar/installiert hast.
Damit kannst Du einen find-Befehl in Perl-Code mit Find::File umwandeln lassen.

Code: (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
$ find2perl . -type d -name "*.rec"
#! /opt/local/perl/bin/perl -w
eval 'exec /opt/local/perl/bin/perl -S $0 ${1+"$@"}'
if 0; #$running_under_some_shell

use strict;
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:
use vars qw/*name *dir *prune/;
*name = *File::Find::name;
*dir = *File::Find::dir;
*prune = *File::Find::prune;

sub wanted;



# Traverse desired filesystems
File::Find::find({wanted => \&wanted}, '.');
exit;


sub wanted {
my ($dev,$ino,$mode,$nlink,$uid,$gid);

(($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
-d _ &&
/^.*\.rec\z/s
&& print("$name\n");
}



Die wanted() Routine prüft dabei mit "-d", ob es sich um ein Verzeichnis handelt und mit einem verankerten Regex, ob die Endung passt. Wenn beides OK ist, wird der "Name" (also der volle Pfad dazu, siehe Doku) ausgegeben.

Das ist auch nachzulesen in der Doku, die man auf Perldoc:Find::File finden kann.



edit:
Selbst gebaut, könnte das so aussehen:

Code (perl): (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#! /usr/bin/perl
use strict;
use warnings;
use 5.010;

use File::Find;

my $basedir = ".";
my $extension = ".rec";

my @matched_dirs;

sub wanted {
    # $File::Find::dir is the current directory name,
    # $_ is the current filename within that directory
    # $File::Find::name is the complete pathname to the file.

    push @matched_dirs, $File::Find::name
      if -d $_ && $_ =~ m/\Q$extension\E$/;

}

find( \&wanted, $basedir );

say "I have found:";
say $_ for @matched_dirs;


edit: Regex mit "\Q \E" versehen um . als . zu werten
Last edited: 2019-01-31 17:05:55 +0100 (CET)
meine Beiträge: I.d.R. alle Angaben ohne Gewähr und auf Linux abgestimmt!
Die Sprache heisst Perl, nicht PERL. - Bitte Crossposts als solche kenntlich machen!

View full thread Verzeichnis Struktur auslesen und in String oder Array speichern