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
How do I list the files in a directory?的更多相关文章
- 网站访问出现 ------ Can not write to cache files, please check directory ./cache/ .
最近在搞微商城时,突然出现了Can not write to cache files, please check directory ./cache/ .这样一个提示, 但最近好像没搞什么大动作,怎么 ...
- [Windows API] Listing the Files in a Directory,可用来数文件夹下有多少个子文件(夹)
转载 #include <windows.h> #include <tchar.h> #include <stdio.h> #include <strsafe ...
- Batch the files in the directory
#!/bin/bash #sourceFolder = /home/bigdatagfts/pl62716/refdata #targetFolder = /home/bigdatagfts/pl62 ...
- C# copy files from source directory to destination file and rename repeated files and does not override
static void CopyFiles() { string sourceDir = @"D:\C\ll"; string destDir = @"D:\LL&quo ...
- Common Linux log files name and usage--reference
reference:http://www.coolcoder.in/2013/12/common-linux-log-files-name-and-usage.html if you spend lo ...
- Files and Directories
Files and Directories Introduction In the previous chapter we coveredthe basic functions that pe ...
- 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 Mainl ...
- How To Get Log, Trace Files In OA Framework Pages And Concurrent Request Programs
Goal Solution References APPLIES TO: Oracle Supplier Lifecycle Management - Version 12.1.2 and l ...
- 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 no ...
随机推荐
- 学习 OAuth2.0
基于浏览器 访问后跳到登录页面,登录成功后跳转到授权页面,授权成功后跳转到redirect_uri指定的地址. 1.请求授权. http://localhost:8080/oauth/authoriz ...
- Oracle脚本笔记
//创建一个表create table 表名(字段名1 varchar2(20) not null);//多个用 , 隔开//添加字段alter table 表名add (字段名2 varchar2 ...
- SVN安装使用小结
SVN在实际的项目开发中有很广泛的用途.一开始接触SVN(Subversion),思路并不清楚,现在总算理清了. 声明:本文并不是系统地对SVN做介绍,而是笔者的使用总结,个人认为的一些要点,可能对初 ...
- 单表60亿记录等大数据场景的MySQL优化和运维之道
此文是根据杨尚刚在[QCON高可用架构群]中,针对MySQL在单表海量记录等场景下,业界广泛关注的MySQL问题的经验分享整理而成,转发请注明出处. 杨尚刚,美图公司数据库高级DBA,负责美图后端数据 ...
- shell 面试题
1. 用sed修改test.txt的23行test为tset: sed –i ‘23s/test/tset/g’ test.txt 2. 查看/web.log第25行第三列的内容. ...
- strip的用法
函数原型 声明:s为字符串,rm为要删除的字符序列 s.strip(rm) 删除s字符串中开头.结尾处,位于 rm删除序列的字符 s.lstrip(rm) 删除s字符串中开头 ...
- height:100%不起作用(无效),div全屏
当父容器是body时,height:100%不起作用(无效),解决办法:在css代码段中添加 html, body{ margin:0; height:100%; } 实现div全屏的时候需要上面那段 ...
- [译] OpenStack Liberty 版本中的53个新变化
一个新的秋季,一个新的OpenStack 版本.OpenStack 的第12个版本,Liberty,在10月15日如期交付,而且目前发行版本已经备好了.那么我们期望能从过去六个月时间的开发中获得些什么 ...
- CSS Sprite雪碧图应用
在写网页过程中,会遇到这种需要使用多个小图标: 如上图中的「女装」文字左边的图标.容易想到的解决方法是为每张图片加入<img>标签,但这样做会增加HTTP请求数量,影响网站加载速度.比这更 ...
- OpenCV 之 图像平滑
1 图像平滑 图像平滑,可用来对图像进行去噪 (noise reduction) 或 模糊化处理 (blurring),实际上图像平滑仍然属于图像空间滤波的一种 (低通滤波) 既然是滤波,则图像中任 ...