How do I list the files in a directory?

原文地址:How do I list the files in a directory?

You want a list of all the files, or all the files matching a certain pattern, or with a certain ending, in a directory

The solution

Reading directories is a bit like reading files. First you open the directory, then you read from it and then you close it. You use a directory handle much as you use a file handle.

Step 1: Opening the directory

To open the directory, we use a function called opendir. You use this much like the open function to open files. In the example below, we open the /tmp directory:

    #!/usr/bin/perl
    use strict;
    use warnings;

    my $directory = ‘/tmp‘;

    opendir (DIR, $directory) or die $!;

Step 2: Reading the directory

To read the files and directories in the directory we use the readdir function. readdir returns the name of each file or directory in the opened directory in turn when used in scalar context, or a list of the names of all files and directories in that directory when used in list context. This means that we can use readdir in a foreach loop (or any other loop construct):

    while (my $file = readdir(DIR)) {

        print "$file\n";

    }

Step 3: Closing the directory

We use the function closedir to close the directory once we are finished with it. Like files, the directory will be closed when the program terminates, but sometimes you will need to explicitly close the directory:

    closedir(DIR);

Directory Listing

Provided your program has sufficient access to the directory being read, readdir will list every file and directory contained in that directory. However, you often will not want all files or directories. For example, it is quite common to exclude all filenames beginning with a period:

    #!/usr/bin/perl

    use strict;
    use warnings;

    my $dir = ‘/tmp‘;

    opendir(DIR, $dir) or die $!;

    while (my $file = readdir(DIR)) {

        # Use a regular expression to ignore files beginning with a period
        next if ($file =~ m/^\./);

	print "$file\n";

    }

    closedir(DIR);
    exit 0;

See further down for a more compact way of doing this.

Find the directories

Sometimes you may want to find all the directories in a directory. Remember that readdir() gives you the names of the files and directories, not the paths. If you want to test a file using any of the standard file tests, you need to use the full path:

    #!/usr/bin/perl

    use strict;
    use warnings;

    my $dir = ‘/tmp‘;

    opendir(DIR, $dir) or die $!;

    while (my $file = readdir(DIR)) {

        # A file test to check that it is a directory
	# Use -f to test for a file
        next unless (-d "$dir/$file");

	print "$file\n";

    }

    closedir(DIR);
    exit 0;

Find files ending in...

Quite often you want to find all files ending in a given suffix. For example, you may want to find all files ending in .txt:

    #!/usr/bin/perl

    use strict;
    use warnings;

    my $dir = ‘/tmp‘;

    opendir(DIR, $dir) or die $!;

    while (my $file = readdir(DIR)) {

        # We only want files
        next unless (-f "$dir/$file");

        # Use a regular expression to find files ending in .txt
        next unless ($file =~ m/\.txt$/);

        print "$file\n";
    }

    closedir(DIR);
    exit 0;

An advanced example

A more advanced example is to use grep to filter out the files you want. The following example (based on a code sample from perldoc -f readdir) gets all the files (not directories) beginning with a period from the open directory. The filenames are found in the array @dots.

    #!/usr/bin/perl

    use strict;
    use warnings;

    my $dir = ‘/tmp‘;

    opendir(DIR, $dir) or die $!;

    my @dots
        = grep {
            /^\./             # Begins with a period
	    && -f "$dir/$_"   # and is a file
	} readdir(DIR);

    # Loop through the array printing out the filenames
    foreach my $file (@dots) {
        print "$file\n";
    }

    closedir(DIR);
    exit 0;

File::Find

You can use the File::Find module to recursively search through a directory (or directories). It is best used when you want to perform some operation on each file. See perldoc File::Find for more information.

glob

Another way of getting a directory listing - if you‘re only interested in the current directory and not in any sub-directories - is to use glob. You can pass glob a pattern (or patterns) to match and it will return any files that match. The example below will list all .pl and .pm files in the current directory:

    #!/usr/bin/perl

    use strict;
    use warnings;

    my @files = glob("*.pl *.pm");

    foreach my $file (@files) {

        print "$file\n";

    }

    exit 0;

See also

    perldoc -f opendir
    perldoc -f readdir
    perldoc -f closedir
    perldoc -f -X
    perldoc -f grep
    perldoc File::Find
    perldoc -f glob
    perldoc File::Glob
时间: 2024-08-10 23:30:41

How do I list the files in a directory?的相关文章

Files and Directories

Files and Directories Introduction In the previous chapter we coveredthe basic functions that perform I/O. The discussion centered on I/O for regular files-opening a file, and reading or writing a file. We'll now look at additionalfeatures of the fil

Lab - Listing Files and Directories

By performing this lab, students will learn how to navigate and manage files and directories. In this lab, you will perform the following tasks: List files and directories Copy, move and delete files and directories Part 1: Files and Directories In t

Save results to different files when executing multi SQL statements in DB Query Analyzer 7.01

1 About DB Query Analyzer DB Query Analyzer is presented by Master Genfeng,Ma from Chinese Mainland. It has English version named 'DB Query Analyzer'and Simplified Chinese version named   . DB Query Analyzer is one of the few excellent Client Tools i

EXTRACT FILES AND IMAGES FROM A SHAREPOINT CONTENT DATABASE

If you ever had the problem where you need to extract files from a SharePoint Content Database or normal SQL Database stored as binary, this post will help you. The script I have included will export all the content from the SharePoint Content Databa

Batch - 忽略FORFILES “no files found” error

ref:https://stackoverflow.com/questions/16820681/suppress-forfiles-no-files-found-error Solution: The solution is to capture the output of the FORFILES command in a FOR loop, search it for strings starting with ERROR, and store the result in a variab

使用Cobbler批量安装操作系统

个人博客地址:http://www.pojun.tech/ 欢迎访问 前言 在实际生产中,我们常常会遇到这样一种情况,就是我们需要同时安装几十甚至上百台服务器,如果我们使用U盘或者光盘的方式的话,或许老板直接就将我们辞退了.这里我们介绍一种能够实现自动化安装操作系统的方式. 我们搭建Cobbler的实验环境是基于CentOS 7.3 -1611 的基础的. 同时这个实验可以帮助你一步步的完成所有的操作,不过,如果你想自定义安装的内容的话,建议你先看本文 自定义kickstart文件 部分,以便有

linux入门基础知识及简单命令介绍

linux入门基础知识介绍 1.计算机硬件组成介绍 计算机主要由cpu(运算器.控制器),内存,I/O,外部存储等构成. cpu主要是用来对二进制数据进行运算操作,它从内存中取出数据,然后进行相应的运算操作.不能从硬盘中直接取数据. 内存从外部存储中取出数据供cpu运存.内存的最小单位是字节(byte) 备注:由于32的cpu逻辑寻址能力最大为32内存单元.因此32位cpu可以访问的最大内存空间为:4GB,算法如下: 2^32=2^10*2^10*2^10*2^2 =1024*1024*1024

ls --help 常用命令

$ ls --help Usage: ls [OPTION]... [FILE]... List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuvSUX nor --sort. Mandatory arguments to long options are mandatory for short options too. -a,

Linux上获取命令帮助的几种方式

一.加参数-h或者--help 例如: [[email protected] ~]# clock -h hwclock - query and set the hardware clock (RTC) Usage: hwclock [function] [options...] Functions:   -h | --help         show this help   -r | --show         read hardware clock and print result