Walk a directory/Non-recursively: Difference between revisions
(Add Rust implementation.) |
m (→{{header|Wren}}: Minor tidy) |
||
(57 intermediate revisions by 44 users not shown) | |||
Line 1: | Line 1: | ||
{{task|File System Operations}} |
{{task|File System Operations}} |
||
Walk a given directory and print the ''names'' of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) |
|||
;Task: |
|||
'''Note:''' This task is for non-recursive methods. These tasks should read a ''single directory'', not an entire directory tree. For code examples that read entire directory trees, see [[Walk Directory Tree]] |
|||
Walk a given directory and print the ''names'' of files matching a given pattern. |
|||
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) |
|||
'''Note:''' This task is for non-recursive methods. These tasks should read a ''single directory'', not an entire directory tree. |
|||
'''Note:''' Please be careful when running any code presented here. |
'''Note:''' Please be careful when running any code presented here. |
||
=={{header|8th}}== |
|||
;Related task: |
|||
<lang forth> |
|||
* [[Walk Directory Tree]] (read entire directory tree). |
|||
"*.c" f:glob \ puts an array of strings with the file names on the top of the stack |
|||
< |
<br><br> |
||
=={{header|11l}}== |
|||
{{trans|Python}} |
|||
<syntaxhighlight lang="11l">L(filename) fs:list_dir(‘/foo/bar’) |
|||
I filename.ends_with(‘.mp3’) |
|||
print(filename)</syntaxhighlight> |
|||
=={{header|68000 Assembly}}== |
=={{header|68000 Assembly}}== |
||
Non-recursive directory walk in Motorola 68000 assembly language under AmigaOs 2.04+ by Thorham. Uses regular Amiga dos pattern matching. |
Non-recursive directory walk in Motorola 68000 assembly language under AmigaOs 2.04+ by Thorham. Uses regular Amiga dos pattern matching. |
||
< |
<syntaxhighlight lang="68000devpac">; |
||
; Non-recursive directory walk for Motorola 68000 under AmigaOs 2.04+ by Thorham |
; Non-recursive directory walk for Motorola 68000 under AmigaOs 2.04+ by Thorham |
||
; |
; |
||
Line 191: | Line 203: | ||
patternParsed |
patternParsed |
||
dcb.b sizeof_patternString*2+2</ |
dcb.b sizeof_patternString*2+2</syntaxhighlight> |
||
=={{header|8080 Assembly}}== |
|||
This program runs under CP/M, which was the commonly used OS on 8080 (and Z80)-based |
|||
machines. The pattern used is the CP/M file pattern, which is the same as a DOS pattern: |
|||
the filename, the extension, and an optional drive letter. |
|||
<syntaxhighlight lang="text">exit: equ 0 ; CP/M syscall to exit |
|||
puts: equ 9 ; CP/M syscall to print a string |
|||
sfirst: equ 17 ; 'Find First' CP/M syscall |
|||
snext: equ 18 ; 'Find Next' CP/M syscall |
|||
FCB: equ 5Ch ; Location of FCB for file given on command line |
|||
org 100h |
|||
lxi d,FCB ; CP/M parses the command line for us automatically |
|||
mvi c,sfirst; and prepares an FCB which we can pass to SFIRST |
|||
call 5 ; immediately. |
|||
lxi d,emsg ; If SFIRST returns an error, there is no file, |
|||
mvi c,puts ; so we should print an error message. |
|||
loop: inr a ; A=FF = error |
|||
jz 5 |
|||
dcr a ; If we _do_ have a file, the directory entry |
|||
rrc ; is located at DTA (80h) + A * 32. 0<=A<=3. |
|||
rrc ; Rotate right twice, moving low bits into high bits, |
|||
stc ; then finally rotate a 1 bit into the top bit. |
|||
rar ; The effect is 000000AB -> 1AB00000. |
|||
inr a ; Finally the filename is at offset 1 in the dirent. |
|||
mvi h,0 ; Set HL = pointer to the filename |
|||
mov l,a |
|||
lxi d,fname ; The filename is stored as 'FILENAMEEXT', but let's |
|||
mvi b,8 ; be nice and print 'FILENAME.EXT\r\n'. |
|||
call memcpy ; Copy filename (wihtout extension) into placeholder |
|||
inx d ; Skip the '.' in the placeholder |
|||
mvi b,3 ; Then copy the extension |
|||
call memcpy |
|||
lxi d,fname ; Then print the formatted filename |
|||
mvi c,puts |
|||
call 5 |
|||
lxi d,FCB ; Find the next file matching the pattern in the FCB |
|||
mvi c,snext ; The result is the same as for SFIRST, so we can |
|||
call 5 ; loop back here, except FF means no more files. |
|||
mvi c,exit ; Arrange for the error routine to instead exit cleanly |
|||
jmp loop |
|||
memcpy: mov a,m ; Copy B bytes from HL to DE |
|||
stax d |
|||
inx h |
|||
inx d |
|||
dcr b |
|||
jnz memcpy |
|||
ret |
|||
emsg: db 'Not Found$' |
|||
fname: db 'XXXXXXXX.XXX',13,10,'$' ; Filename placeholder</syntaxhighlight> |
|||
{{out}} |
|||
<pre style='height: 50ex;'>I>dir |
|||
I: TINST COM : TINST DTA : TINST MSG : TURBO COM |
|||
I: TURBO MSG : TURBO OVR : WALKDIR ASM : WALKDIR PRN |
|||
I: WALKDIR HEX : WALKDIR COM |
|||
I>walkdir walkdir.* |
|||
WALKDIR .ASM |
|||
WALKDIR .PRN |
|||
WALKDIR .HEX |
|||
WALKDIR .COM |
|||
I>walkdir *.com |
|||
TINST .COM |
|||
TURBO .COM |
|||
WALKDIR .COM |
|||
I>walkdir foobar.baz |
|||
Not Found |
|||
I>dir a:*.asm |
|||
A: COUNT ASM : DETECT ASM : SUBLEQ ASM : LUHN ASM |
|||
I>walkdir a:*.asm |
|||
COUNT .ASM |
|||
DETECT .ASM |
|||
SUBLEQ .ASM |
|||
LUHN .ASM |
|||
</pre> |
|||
=={{header|8th}}== |
|||
<syntaxhighlight lang="forth"> |
|||
"*.c" f:glob \ puts an array of strings with the file names on the top of the stack |
|||
</syntaxhighlight> |
|||
=={{header|Action!}}== |
|||
The attached result has been obtained under DOS 2.5. |
|||
<syntaxhighlight lang="action!">PROC GetFileName(CHAR ARRAY line,fname) |
|||
BYTE i,len |
|||
len=0 |
|||
i=3 |
|||
FOR i=3 TO 10 |
|||
DO |
|||
IF line(i)=32 THEN EXIT FI |
|||
len==+1 |
|||
fname(len)=line(i) |
|||
OD |
|||
len==+1 |
|||
fname(len)='. |
|||
FOR i=11 TO 13 |
|||
DO |
|||
IF line(i)=32 THEN EXIT FI |
|||
len==+1 |
|||
fname(len)=line(i) |
|||
OD |
|||
fname(0)=len |
|||
RETURN |
|||
PROC Dir(CHAR ARRAY filter) |
|||
CHAR ARRAY line(255),fname(255) |
|||
BYTE dev=[1] |
|||
PrintE(filter) |
|||
Close(dev) |
|||
Open(dev,filter,6) |
|||
DO |
|||
InputSD(dev,line) |
|||
IF line(0)=0 OR line(0)>0 AND line(1)#32 THEN |
|||
EXIT |
|||
FI |
|||
GetFileName(line,fname) |
|||
Put(32) PrintE(fname) |
|||
OD |
|||
Close(dev) |
|||
PutE() |
|||
RETURN |
|||
PROC Main() |
|||
Dir("D:*.*") |
|||
Dir("H1:X*.*") |
|||
Dir("H1:?????.ACT") |
|||
Dir("H1:??F*.*") |
|||
RETURN</syntaxhighlight> |
|||
{{out}} |
|||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Walk_a_directory_non-recursively.png Screenshot from Atari 8-bit computer] |
|||
<pre> |
|||
D:*.* |
|||
DOS.SYS |
|||
DUP.SYS |
|||
INPUT.TXT |
|||
H1:X*.* |
|||
XIAOL_24.ACT |
|||
XML_O_CU.ACT |
|||
H1:?????.ACT |
|||
AB_3D.ACT |
|||
BREAK.ACT |
|||
CUSIP.ACT |
|||
SIEVE.ACT |
|||
SLEEP.ACT |
|||
WHILE.ACT |
|||
H1:??F*.* |
|||
HOFST_34.ACT |
|||
INFINITE.ACT |
|||
UTF8__P2.ACT |
|||
</pre> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
{{works with|GCC|4.12}} |
{{works with|GCC|4.12}} |
||
< |
<syntaxhighlight lang="ada">with Ada.Directories; use Ada.Directories; |
||
with Ada.Text_IO; use Ada.Text_IO; |
with Ada.Text_IO; use Ada.Text_IO; |
||
Line 213: | Line 384: | ||
End_Search (Search); |
End_Search (Search); |
||
end Walk_Directory;</ |
end Walk_Directory;</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Line 219: | Line 390: | ||
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386 - uses non-standard library routines ''get directory'' and'' grep in string''.}} |
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386 - uses non-standard library routines ''get directory'' and'' grep in string''.}} |
||
<!-- {{does not work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386 - ''get directory'' and'' grep in string'' not available in any library ... yet}} --> |
<!-- {{does not work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386 - ''get directory'' and'' grep in string'' not available in any library ... yet}} --> |
||
< |
<syntaxhighlight lang="algol68">INT match=0, no match=1, out of memory error=2, other error=3; |
||
[]STRING directory = get directory("."); |
[]STRING directory = get directory("."); |
||
Line 227: | Line 398: | ||
print((file, new line)) |
print((file, new line)) |
||
FI |
FI |
||
OD</ |
OD</syntaxhighlight> |
||
{{out|Sample output}} |
{{out|Sample output}} |
||
<pre> |
<pre> |
||
Line 243: | Line 414: | ||
AppleScript itself has limited built-in file system access. Typically, the Mac OS Finder is used to gather such information. |
AppleScript itself has limited built-in file system access. Typically, the Mac OS Finder is used to gather such information. |
||
To list all file/folders in the root directory: |
To list all file/folders in the root directory: |
||
< |
<syntaxhighlight lang="applescript">tell application "Finder" to return name of every item in (startup disk) |
||
--> EXAMPLE RESULT: {"Applications", "Developer", "Library", "System", "Users"}</ |
--> EXAMPLE RESULT: {"Applications", "Developer", "Library", "System", "Users"}</syntaxhighlight> |
||
To list all pdf files in user's home directory: |
To list all pdf files in user's home directory: |
||
< |
<syntaxhighlight lang="applescript">tell application "Finder" to return name of every item in (path to documents folder from user domain) whose name ends with "pdf" |
||
--> EXAMPLE RESULT: {"About Stacks.pdf", "Test.pdf"}</ |
--> EXAMPLE RESULT: {"About Stacks.pdf", "Test.pdf"}</syntaxhighlight> |
||
The key clause is the <code>whose</code> modifier keyword. The Finder can interpret many variations, including such terms as <code>whose name begins with</code>, <code>whose name contains</code>, etc. As well as boolean combinations: |
The key clause is the <code>whose</code> modifier keyword. The Finder can interpret many variations, including such terms as <code>whose name begins with</code>, <code>whose name contains</code>, etc. As well as boolean combinations: |
||
< |
<syntaxhighlight lang="applescript">tell application "Finder" to return name of every item in (path to documents folder from user domain) whose name does not contain "about" and name ends with "pdf" |
||
--> RETURNS: {"Test.pdf"}</ |
--> RETURNS: {"Test.pdf"}</syntaxhighlight> |
||
The Finder also supports the <code>entire contents</code> modifier keyword, which effectively performs a recursive directory scan without recursion. |
The Finder also supports the <code>entire contents</code> modifier keyword, which effectively performs a recursive directory scan without recursion. |
||
< |
<syntaxhighlight lang="applescript">tell application "Finder" to return name of every item in entire contents of (path to documents folder from user domain) whose name ends with "pdf"</syntaxhighlight> |
||
---- |
|||
Nowadays, it's more usual to use macOS's System Events application for this kind of task as it's very much faster than the Finder, especially with 'whose' filters. However, its results, unlike the Finder's, aren't sorted by the items' names and it includes results for hidden items too if these match the criteria. |
|||
<syntaxhighlight lang="applescript">tell application "System Events" to return name of every item in documents folder whose name extension is "pdf" |
|||
--> EXAMPLE RESULT: {"ShellScripting.pdf", "RFC 4180 (CSV spec).pdf", "About Stacks.pdf", "AppleScriptLanguageGuide.pdf", "robinson_jeffers_2004_9.pdf", "DiskWarrior Manual.pdf", "RFC 2445 (iCalendar spec).pdf", "Artistic Orchestration.pdf"}</syntaxhighlight> |
|||
Intermediate in speed between the Finder and System Events are shell scripts, which are handy if you're more comfortable with shell scripts than with AppleScript. |
|||
<syntaxhighlight lang="applescript">set docsFolderPath to POSIX path of (path to documents folder) |
|||
-- By default, "ls" returns file names sorted by character code, so save the sorting until the end and do it case-insensitively. |
|||
set shellCommandText to "ls -f " & quoted form of docsFolderPath & " | grep -i '\\.pdf$' | sort -f" |
|||
return paragraphs of (do shell script shellCommandText) |
|||
--> EXAMPLE RESULT: {"About Stacks.pdf", "AppleScriptLanguageGuide.pdf", "Artistic Orchestration.pdf", "DiskWarrior Manual.pdf", "RFC 2445 (iCalendar spec).pdf", "RFC 4180 (CSV spec).pdf", "robinson_jeffers_2004_9.pdf", "ShellScripting.pdf"}</syntaxhighlight> |
|||
Best of all for speed and sorting, although requiring somewhat more code, are the Foundation methods available through AppleScriptObjC. |
|||
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later |
|||
use framework "Foundation" |
|||
use scripting additions |
|||
set docsFolderURL to current application's class "NSURL"'s fileURLWithPath:(POSIX path of (path to documents folder)) |
|||
-- Get NSURLs for the folder's visible contents. |
|||
tell current application's class "NSFileManager"'s defaultManager() to ¬ |
|||
set visibleItems to its contentsOfDirectoryAtURL:(docsFolderURL) includingPropertiesForKeys:({}) ¬ |
|||
options:(current application's NSDirectoryEnumerationSkipsHiddenFiles) |error|:(missing value) |
|||
-- Filter case-insensitively for those whose names have ".pdf" extensions. |
|||
set filter to current application's class "NSPredicate"'s predicateWithFormat:("pathExtension ==[c] 'pdf'") |
|||
set PDFs to visibleItems's filteredArrayUsingPredicate:(filter) |
|||
-- Get the names of any matching items. |
|||
set pdfNames to PDFs's valueForKey:("lastPathComponent") |
|||
-- Sort these case-insensitively and considering numerics. |
|||
set pdfNames to pdfNames's sortedArrayUsingSelector:("localizedStandardCompare:") |
|||
-- Return the result as an AppleScript list of text. |
|||
return pdfNames as list |
|||
--> EXAMPLE RESULT: {"About Stacks.pdf", "AppleScriptLanguageGuide.pdf", "Artistic Orchestration.pdf", "DiskWarrior Manual.pdf", "RFC 2445 (iCalendar spec).pdf", "RFC 4180 (CSV spec).pdf", "robinson_jeffers_2004_9.pdf", "ShellScripting.pdf"}</syntaxhighlight> |
|||
=={{header|Arturo}}== |
|||
<syntaxhighlight lang="rebol">; list all files at current path |
|||
print list "." |
|||
; get all files at given path |
|||
; and select only the ones we want |
|||
; just select the files with .md extension |
|||
select list "some/path" |
|||
=> [".md" = extract.extension] |
|||
; just select the files that contain "test" |
|||
select list "some/path" |
|||
=> [in? "test"]</syntaxhighlight> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
Display all INI files in Windows directory. |
Display all INI files in Windows directory. |
||
< |
<syntaxhighlight lang="autohotkey">Loop, %A_WinDir%\*.ini |
||
out .= A_LoopFileName "`n" |
out .= A_LoopFileName "`n" |
||
MsgBox,% out</ |
MsgBox,% out</syntaxhighlight> |
||
=={{header|BaCon}}== |
|||
This code will print all files in the current directory ".", separated by a newline symbol: |
|||
<syntaxhighlight lang="qbasic">PRINT WALK$(".", 1, ".+", FALSE, NL$)</syntaxhighlight> |
|||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
Line 264: | Line 490: | ||
DOS wildcards are rather underpowered when compared to... well... anything else. |
DOS wildcards are rather underpowered when compared to... well... anything else. |
||
{{works with|FreeBASIC}} |
|||
< |
<syntaxhighlight lang="qbasic">DECLARE SUB show (pattern AS STRING) |
||
show "*.*" |
show "*.*" |
||
Line 276: | Line 502: | ||
f = DIR$ |
f = DIR$ |
||
LOOP |
LOOP |
||
END SUB</ |
END SUB</syntaxhighlight> |
||
=={{header|BASIC256}}== |
|||
<syntaxhighlight lang="basic256">call show ("c:\") |
|||
end |
|||
subroutine show (pattern$) |
|||
f$ = dir(pattern$) |
|||
while length(f$) |
|||
print f$ |
|||
f$ = dir |
|||
end while |
|||
end subroutine</syntaxhighlight> |
|||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
A simple command that displays all EXE files in System32 directory non-recursively. |
A simple command that displays all EXE files in System32 directory non-recursively. |
||
< |
<syntaxhighlight lang="dos">dir /b "%windir%\system32\*.exe"</syntaxhighlight> |
||
The same command inside FOR loop: |
The same command inside FOR loop: |
||
*Inside a Batch File: |
*Inside a Batch File: |
||
< |
<syntaxhighlight lang="dos">@for /F "tokens=*" %%F in ('dir /b "%windir%\system32\*.exe"') do echo %%F</syntaxhighlight> |
||
*Command-line: |
*Command-line: |
||
< |
<syntaxhighlight lang="dos">for /F "tokens=*" %F in ('dir /b "%windir%\system32\*.exe"') do echo %F</syntaxhighlight> |
||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
< |
<syntaxhighlight lang="bbcbasic"> directory$ = "C:\Windows\" |
||
pattern$ = "*.ini" |
pattern$ = "*.ini" |
||
PROClistdir(directory$ + pattern$) |
PROClistdir(directory$ + pattern$) |
||
Line 305: | Line 543: | ||
SYS "FindClose", sh% |
SYS "FindClose", sh% |
||
ENDIF |
ENDIF |
||
ENDPROC</ |
ENDPROC</syntaxhighlight> |
||
=={{header|C}}== |
=={{header|C}}== |
||
Line 311: | Line 549: | ||
{{works with|POSIX|.1-2001}} |
{{works with|POSIX|.1-2001}} |
||
In this example, the pattern is a [[POSIX]] extended regular expression. |
In this example, the pattern is a [[POSIX]] extended regular expression. |
||
< |
<syntaxhighlight lang="c">#include <sys/types.h> |
||
#include <dirent.h> |
#include <dirent.h> |
||
#include <regex.h> |
#include <regex.h> |
||
Line 344: | Line 582: | ||
walker(".", ".\\.c$"); |
walker(".", ".\\.c$"); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
|||
<syntaxhighlight lang="csharp">using System; |
|||
using System.IO; |
|||
namespace DirectoryWalk |
|||
{ |
|||
class Program |
|||
{ |
|||
static void Main(string[] args) |
|||
{ |
|||
string[] filePaths = Directory.GetFiles(@"c:\MyDir", "a*"); |
|||
foreach (string filename in filePaths) |
|||
Console.WriteLine(filename); |
|||
} |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
{{libheader|boost|1.50.0}} |
{{libheader|boost|1.50.0}} |
||
< |
<syntaxhighlight lang="cpp">#include "boost/filesystem.hpp" |
||
#include "boost/regex.hpp" |
#include "boost/regex.hpp" |
||
#include <iostream> |
#include <iostream> |
||
Line 370: | Line 626: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{libheader|std|C++17}} |
|||
<syntaxhighlight lang="cpp"> |
|||
<lang csharp>using System; |
|||
#include <filesystem> |
|||
using System.IO; |
|||
#include <iostream> |
|||
namespace |
namespace fs = std::filesystem; |
||
{ |
|||
int main() { |
|||
class Program |
|||
fs::path current_dir("."); |
|||
{ |
|||
// list all files containing an mp3 extension |
|||
static void Main(string[] args) |
|||
for (auto &file : fs::directory_iterator(current_dir)) { |
|||
{ |
|||
if (file.path().extension() == ".mp3") |
|||
string[] filePaths = Directory.GetFiles(@"c:\MyDir", "a*"); |
|||
std::cout << file.path().filename().string() << std::endl; |
|||
} |
|||
Console.WriteLine(filename); |
|||
}</syntaxhighlight> |
|||
} |
|||
} |
|||
=={{header|Clojure}}== |
|||
} |
|||
Using Java 8's [https://docs.oracle.com/javase/8/docs/api/java/nio/file/FileSystem.html#getPathMatcher-java.lang.String- PathMatcher] patterns. |
|||
</lang> |
|||
<syntaxhighlight lang="clojure">(import java.nio.file.FileSystems) |
|||
(defn match-files [f pattern] |
|||
(.matches (.getPathMatcher (FileSystems/getDefault) (str "glob:*" pattern)) (.toPath f))) |
|||
(defn walk-directory [dir pattern] |
|||
(let [directory (clojure.java.io/file dir)] |
|||
(map #(.getPath %) (filter #(match-files % pattern) (.listFiles directory))))) |
|||
</syntaxhighlight> |
|||
=={{header|ColdFusion}}== |
=={{header|ColdFusion}}== |
||
This example display all files and directories directly under '''C:\temp''' that end with ''.html'' |
This example display all files and directories directly under '''C:\temp''' that end with ''.html'' |
||
< |
<syntaxhighlight lang="cfm"><cfdirectory action="list" directory="C:\temp" filter="*.html" name="dirListing"> |
||
<cfoutput query="dirListing"> |
<cfoutput query="dirListing"> |
||
#dirListing.name# (#dirListing.type#)<br> |
#dirListing.name# (#dirListing.type#)<br> |
||
</cfoutput></ |
</cfoutput></syntaxhighlight> |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun walk-directory (directory pattern) |
||
(directory (merge-pathnames pattern directory)))</ |
(directory (merge-pathnames pattern directory)))</syntaxhighlight> |
||
Uses the filename pattern syntax provided by the CL implementation. |
Uses the filename pattern syntax provided by the CL implementation. |
||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">void main() { |
||
import std.stdio, std.file; |
import std.stdio, std.file; |
||
dirEntries(".", "*.*", SpanMode.shallow).writeln; |
dirEntries(".", "*.*", SpanMode.shallow).writeln; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|DCL}}== |
=={{header|DCL}}== |
||
<pre>* matches any number of characters |
<pre>* matches any number of characters |
||
& matches exactly any one character</pre> |
& matches exactly any one character</pre> |
||
<lang>$ loop: |
<syntaxhighlight lang="text">$ loop: |
||
$ f = f$search( p1 ) |
$ f = f$search( p1 ) |
||
$ if f .eqs. "" then $ exit |
$ if f .eqs. "" then $ exit |
||
$ write sys$output f |
$ write sys$output f |
||
$ goto loop</ |
$ goto loop</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>$ @walk_a_directory *.* |
<pre>$ @walk_a_directory *.* |
||
Line 429: | Line 697: | ||
USERS:[DAVID]WALK_A_DIRECTORY.COM;1 |
USERS:[DAVID]WALK_A_DIRECTORY.COM;1 |
||
$ </pre> |
$ </pre> |
||
=={{header|Delphi}}== |
|||
=== Hand-coded === |
|||
See: [[Pascal]] |
|||
=== Using System.IOUtils === |
|||
{{libheader| System.IOUtils}} |
|||
<syntaxhighlight lang="delphi"> |
|||
program Walk_a_directory; |
|||
{$APPTYPE CONSOLE} |
|||
{$R *.res} |
|||
uses |
|||
System.IOUtils; |
|||
var |
|||
Files: TArray<string>; |
|||
FileName, Directory: string; |
|||
begin |
|||
Directory := TDirectory.GetCurrentDirectory; // dir = '.', work to |
|||
Files := TDirectory.GetFiles(Directory, '*.*'); |
|||
for FileName in Files do |
|||
begin |
|||
Writeln(FileName); |
|||
end; |
|||
Readln; |
|||
end. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
D:\Rosettacode\Walk_a_directory\Win32\Debug\Walk_a_directory.exe |
|||
</pre> |
|||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang="e">def walkDirectory(directory, pattern) { |
||
for name => file ? (name =~ rx`.*$pattern.*`) in directory { |
for name => file ? (name =~ rx`.*$pattern.*`) in directory { |
||
println(name) |
println(name) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Example: |
Example: |
||
< |
<syntaxhighlight lang="e">? walkDirectory(<file:~>, "bash_") |
||
.bash_history |
.bash_history |
||
.bash_profile |
.bash_profile |
||
.bash_profile~</ |
.bash_profile~</syntaxhighlight> |
||
=={{header|Elena}}== |
|||
ELENA 6.x: |
|||
<syntaxhighlight lang="elena">import system'io; |
|||
import system'routines; |
|||
import extensions'routines; |
|||
public program() |
|||
{ |
|||
var dir := Directory.assign("c:\MyDir"); |
|||
dir.getFiles("a.*").forEach(printingLn); |
|||
}</syntaxhighlight> |
|||
=={{header|Elixir}}== |
|||
<syntaxhighlight lang="elixir"># current directory |
|||
IO.inspect File.ls! |
|||
dir = "/users/public" |
|||
IO.inspect File.ls!(dir)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
["check.exs", "e.bat", "foo", "input.txt", "test.beam", "test.exs", "test.txt"] |
|||
["Desktop", "desktop.ini", "Documents", "Downloads", "Favorites", "Libraries", |
|||
"Music", "Pictures", "Recorded TV", "Videos"] |
|||
</pre> |
|||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
Line 446: | Line 780: | ||
directory, optionally restricted to those matching a regexp. |
directory, optionally restricted to those matching a regexp. |
||
< |
<syntaxhighlight lang="lisp">(directory-files "/some/dir/name" |
||
nil ;; just the filenames, not full paths |
nil ;; just the filenames, not full paths |
||
"\\.c\\'" ;; regexp |
"\\.c\\'" ;; regexp |
||
t) ;; don't sort the filenames |
t) ;; don't sort the filenames |
||
;;=> ("foo.c" "bar.c" ...)</syntaxhighlight> |
|||
=> |
|||
("foo.c" "bar.c" ...)</lang> |
|||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
Line 466: | Line 799: | ||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">include file.e |
||
procedure show(sequence pattern) |
procedure show(sequence pattern) |
||
Line 477: | Line 810: | ||
end procedure |
end procedure |
||
show("*.*")</ |
show("*.*")</syntaxhighlight> |
||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp">System.IO.Directory.GetFiles("c:\\temp", "*.xml") |
||
|> Array.iter (printfn "%s")</ |
|> Array.iter (printfn "%s")</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
Using unix globs. Also see the "directory." in basis/tools/files.factor. |
Using unix globs. Also see the "directory." in basis/tools/files.factor. |
||
< |
<syntaxhighlight lang="factor">USING: globs io io.directories kernel regexp sequences ; |
||
IN: walk-directory-non-recursively |
IN: walk-directory-non-recursively |
||
: print-files ( path pattern -- ) |
: print-files ( path pattern -- ) |
||
[ directory-files ] [ <glob> ] bi* [ matches? ] curry filter |
[ directory-files ] [ <glob> ] bi* [ matches? ] curry filter |
||
[ print ] each ;</ |
[ print ] each ;</syntaxhighlight> |
||
Ex: |
Ex: |
||
( scratchpad ) "." "*.txt" print-files |
( scratchpad ) "." "*.txt" print-files |
||
Line 498: | Line 831: | ||
{{works with|gforth|0.6.2}} |
{{works with|gforth|0.6.2}} |
||
Gforth's directory walking functions are tied to the POSIX ''dirent'' functions, used by the C langauge entry above. Forth doesn't have regex support, so a simple filter function is used instead. |
Gforth's directory walking functions are tied to the POSIX ''dirent'' functions, used by the C langauge entry above. Forth doesn't have regex support, so a simple filter function is used instead. |
||
< |
<syntaxhighlight lang="forth">defer ls-filter ( name len -- ? ) |
||
: ls-all 2drop true ; |
: ls-all 2drop true ; |
||
: ls-visible drop c@ [char] . <> ; |
: ls-visible drop c@ [char] . <> ; |
||
Line 522: | Line 855: | ||
' c-file? is ls-filter |
' c-file? is ls-filter |
||
s" ." ls</ |
s" ." ls</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
|||
{{trans|BASIC}} |
|||
<syntaxhighlight lang="freebasic"> |
|||
Sub show (pattern As String) |
|||
Dim As String f = Dir$(pattern) |
|||
While Len(f) |
|||
Print f |
|||
f = Dir$ |
|||
Wend |
|||
End Sub |
|||
show "*.*" |
|||
Sleep |
|||
</syntaxhighlight> |
|||
=={{header|Frink}}== |
|||
This prints the names of all of the files in the current directory that end with <CODE>.frink</CODE> using a regular expression. |
|||
<syntaxhighlight lang="frink">for f = select[files["."], {|f1| f1.getName[] =~ %r/\.frink$/}] |
|||
println[f.getName[]]</syntaxhighlight> |
|||
{{out}} |
|||
<pre>UTMtest.frink |
|||
mersennetest.frink |
|||
piChudnovskyNew.frink |
|||
showFonts.frink |
|||
graphicalSieve.frink |
|||
... |
|||
</pre> |
|||
=={{header|FutureBasic}}== |
|||
<syntaxhighlight lang="futurebasic"> |
|||
include "NSLog.incl" |
|||
void local fn EnumerateDirectoryAtURL( dirURL as CFURLRef ) |
|||
NSDirectoryEnumerationOptions options = NSDirectoryEnumerationSkipsPackageDescendants + ¬ |
|||
NSDirectoryEnumerationSkipsHiddenFiles + ¬ |
|||
NSDirectoryEnumerationSkipsSubdirectoryDescendants |
|||
DirectoryEnumeratorRef enumerator = fn FileManagerEnumeratorAtURL( dirURL, NULL, options, NULL, NULL ) |
|||
CFURLRef url = fn EnumeratorNextObject( enumerator ) |
|||
while ( url ) |
|||
if ( fn StringIsEqual( fn URLPathExtension( url ), @"fb" ) ) |
|||
NSLog(@"%@",fn URLLastPathComponent( url )) |
|||
end if |
|||
url = fn EnumeratorNextObject( enumerator ) |
|||
wend |
|||
end fn |
|||
fn EnumerateDirectoryAtURL( fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask ) ) |
|||
HandleEvents |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
ListFormatter.fb |
|||
ObjectProperty1.fb |
|||
Archimedean Spiral with Bezier Curve.fb |
|||
FB3D.fb |
|||
lenArray.fb |
|||
Rosettacode Random Noise v04.fb |
|||
AssociatedObject.fb |
|||
</pre> |
|||
=={{header|Gambas}}== |
|||
'''[https://gambas-playground.proko.eu/?gist=c5fde952fecd1d7052101b1e2287f2ff Click this link to run this code]''' |
|||
<syntaxhighlight lang="gambas">Public Sub Main() |
|||
Dim sTemp As String |
|||
For Each sTemp In Dir("/etc", "*.d") |
|||
Print sTemp |
|||
Next |
|||
End</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
profile.d |
|||
rc1.d |
|||
rc4.d |
|||
rcS.d |
|||
binfmt.d |
|||
init.d |
|||
rc5.d |
|||
rc2.d |
|||
</pre> |
|||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 534: | Line 954: | ||
func main() { |
func main() { |
||
fmt.Println(filepath.Glob("*.go")) |
fmt.Println(filepath.Glob("*.go")) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
< |
<syntaxhighlight lang="groovy">// *** print *.txt files in current directory |
||
new File('.').eachFileMatch(~/.*\.txt/) { |
new File('.').eachFileMatch(~/.*\.txt/) { |
||
println it |
println it |
||
Line 545: | Line 965: | ||
new File('/foo/bar').eachFileMatch(~/.*\.txt/) { |
new File('/foo/bar').eachFileMatch(~/.*\.txt/) { |
||
println it |
println it |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Hare}}== |
|||
<syntaxhighlight lang="hare">use fmt; |
|||
use glob; |
|||
export fn main() void = { |
|||
ls("/etc/*.conf"); |
|||
}; |
|||
fn ls(pattern: str) void = { |
|||
let gen = glob::glob(pattern, glob::flags::NONE); |
|||
defer glob::finish(&gen); |
|||
for (true) match (glob::next(&gen)) { |
|||
case void => |
|||
break; |
|||
case glob::failure => |
|||
continue; |
|||
case let s: str => |
|||
fmt::printfln("{}", s)!; |
|||
}; |
|||
};</syntaxhighlight> |
|||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
{{works with|GHC|GHCi|6.6}} |
{{works with|GHC|GHCi|6.6}} |
||
In this example, the pattern is a POSIX extended regular expression. |
In this example, the pattern is a POSIX extended regular expression. |
||
< |
<syntaxhighlight lang="haskell">import System.Directory |
||
import Text.Regex |
import Text.Regex |
||
import Data.Maybe |
import Data.Maybe |
||
Line 559: | Line 1,000: | ||
mapM_ putStrLn $ filter (isJust.(matchRegex $ mkRegex pattern)) filenames |
mapM_ putStrLn $ filter (isJust.(matchRegex $ mkRegex pattern)) filenames |
||
main = walk "." ".\\.hs$"</ |
main = walk "." ".\\.hs$"</syntaxhighlight> |
||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
More on [http://www.HicEst.com/SYSTEM.htm SYSTEM], [http://www.HicEst.com/OPEN.htm OPEN], [http://www.HicEst.com/indexfnc.htm INDEX] |
More on [http://www.HicEst.com/SYSTEM.htm SYSTEM], [http://www.HicEst.com/OPEN.htm OPEN], [http://www.HicEst.com/indexfnc.htm INDEX] |
||
< |
<syntaxhighlight lang="hicest">CHARACTER dirtxt='dir.txt', filename*80 |
||
SYSTEM(DIR='*.*', FIle=dirtxt) ! "file names", length, attrib, Created, LastWrite, LastAccess |
SYSTEM(DIR='*.*', FIle=dirtxt) ! "file names", length, attrib, Created, LastWrite, LastAccess |
||
Line 572: | Line 1,013: | ||
! write file names with extensions "txt", or "hic", or "jpg" (case insensitive) using RegEx option =128: |
! write file names with extensions "txt", or "hic", or "jpg" (case insensitive) using RegEx option =128: |
||
IF( INDEX(filename, "\.txt|\.hic|\.jpg", 128) ) WRITE() filename |
IF( INDEX(filename, "\.txt|\.hic|\.jpg", 128) ) WRITE() filename |
||
ENDDO</ |
ENDDO</syntaxhighlight> |
||
=={{header|IDL}}== |
|||
<lang idl>f = file_search('*.txt', count=cc) |
|||
if cc gt 0 then print,f</lang> |
|||
(IDL is an array language - very few things are ever done in 'loops'.) |
|||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
This uses Unicon extensions for ''stat'' and to read directories. Icon can uses ''system'' to accomplish the same objective. |
This uses Unicon extensions for ''stat'' and to read directories. Icon can uses ''system'' to accomplish the same objective. |
||
< |
<syntaxhighlight lang="icon">procedure main() |
||
every write(getdirs(".","icn")) # writes out all directories from the current directory down |
every write(getdirs(".","icn")) # writes out all directories from the current directory down |
||
end |
end |
||
Line 594: | Line 1,030: | ||
close(d) |
close(d) |
||
} |
} |
||
end</ |
end</syntaxhighlight> |
||
=={{header|IDL}}== |
|||
<syntaxhighlight lang="idl">f = file_search('*.txt', count=cc) |
|||
if cc gt 0 then print,f</syntaxhighlight> |
|||
(IDL is an array language - very few things are ever done in 'loops'.) |
|||
=={{header|J}}== |
=={{header|J}}== |
||
< |
<syntaxhighlight lang="j">require 'dir' |
||
0 dir '*.png' |
0 dir '*.png' |
||
0 dir '/mydir/*.txt'</ |
0 dir '/mydir/*.txt'</syntaxhighlight> |
||
The verb <tt>dir</tt> supports a number of reporting options determined by its left argument. A left argument of <tt>0</tt> reports just the file names. |
The verb <tt>dir</tt> supports a number of reporting options determined by its left argument. A left argument of <tt>0</tt> reports just the file names. |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang="java">File dir = new File("/foo/bar"); |
||
String[] contents = dir.list(); |
String[] contents = dir.list(); |
||
for (String file : contents) |
for (String file : contents) |
||
if (file.endsWith(".mp3")) |
if (file.endsWith(".mp3")) |
||
System.out.println(file);</ |
System.out.println(file);</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
{{works with|JScript}} |
{{works with|JScript}} |
||
< |
<syntaxhighlight lang="javascript">var fso = new ActiveXObject("Scripting.FileSystemObject"); |
||
var dir = fso.GetFolder('test_folder'); |
var dir = fso.GetFolder('test_folder'); |
||
Line 633: | Line 1,074: | ||
} |
} |
||
walkDirectory(dir, '\\.txt$');</ |
walkDirectory(dir, '\\.txt$');</syntaxhighlight> |
||
=={{header|Julia}}== |
|||
{{works with|Julia|0.6}} |
|||
<syntaxhighlight lang="julia">for filename in readdir("/foo/bar") |
|||
if endswith(filename, ".mp3") |
|||
print(filename) |
|||
end |
|||
end</syntaxhighlight> |
|||
=={{header|Kotlin}}== |
|||
<syntaxhighlight lang="scala">// version 1.1.2 |
|||
import java.io.File |
|||
fun walkDirectory(dirPath: String, pattern: Regex): List<String> { |
|||
val d = File(dirPath) |
|||
require(d.exists() && d.isDirectory()) |
|||
return d.list().filter { it.matches(pattern) } |
|||
} |
|||
fun main(args: Array<String>) { |
|||
val r = Regex("""^a.*\.h$""") // get all C header files beginning with 'a' |
|||
val files = walkDirectory("/usr/include", r) |
|||
for (file in files) println(file) |
|||
}</syntaxhighlight> |
|||
Sample output (Ubuntu v14.04): |
|||
{{out}} |
|||
<pre> |
|||
argp.h |
|||
alloca.h |
|||
ar.h |
|||
aliases.h |
|||
autosprintf.h |
|||
aio.h |
|||
assert.h |
|||
argz.h |
|||
</pre> |
|||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang="lasso">local(matchingfilenames = array) |
||
dir('.') -> foreach => {#1 >> 'string' ? #matchingfilenames -> insert(#1)} |
dir('.') -> foreach => {#1 >> 'string' ? #matchingfilenames -> insert(#1)} |
||
#matchingfilenames</ |
#matchingfilenames</syntaxhighlight> |
||
-> array(mystrings.html, a_string_file.txt) |
-> array(mystrings.html, a_string_file.txt) |
||
=={{header|Lingo}}== |
|||
<syntaxhighlight lang="lingo">-- Usage: printFiles("C:\scripts", ".ls") |
|||
on printFiles (dir, fileType) |
|||
i = 1 |
|||
sub = fileType.length -1 |
|||
repeat while TRUE |
|||
fn = getNthFileNameInFolder(dir, i) |
|||
if fn = EMPTY then exit repeat |
|||
i = i+1 |
|||
if fn.length<fileType.length then next repeat |
|||
if fn.char[fn.length-sub..fn.length]=fileType then put fn |
|||
end repeat |
|||
end</syntaxhighlight> |
|||
=={{header|LiveCode}}== |
|||
<syntaxhighlight lang="livecode">set the defaultFolder to the documents folder -- the documents folder is a "specialFolderPath" |
|||
put the files into docfiles |
|||
filter docfiles with "*.txt" |
|||
put docfiles</syntaxhighlight> |
|||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
Lua itself is extremely spartanic as it is meant for embedding. Reading out a directory is not something that a minimal standard C library can do, and so minimal Lua without native extension libraries can't do it either. But lfs (LuaFileSystem) is about as standard an extension as it gets, so we use that. |
Lua itself is extremely spartanic as it is meant for embedding. Reading out a directory is not something that a minimal standard C library can do, and so minimal Lua without native extension libraries can't do it either. But lfs (LuaFileSystem) is about as standard an extension as it gets, so we use that. |
||
< |
<syntaxhighlight lang="lua">require "lfs" |
||
directorypath = "." -- current working directory |
directorypath = "." -- current working directory |
||
for filename in lfs.dir(directorypath) do |
for filename in lfs.dir(directorypath) do |
||
Line 651: | Line 1,150: | ||
print(filename) |
print(filename) |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
Although Lua is spartanic, it still provides functions such as os.execute([command]) and io.popen(prog [, mode]). Below an example for Windows users having io.popen at their disposal. Mind you, it may pop-up a command window. |
|||
<syntaxhighlight lang="lua">-- Gets the output of given program as string |
|||
-- Note that io.popen is not available on all platforms |
|||
local function getOutput(prog) |
|||
local file = assert(io.popen(prog, "r")) |
|||
local output = assert(file:read("*a")) |
|||
file:close() |
|||
return output |
|||
end |
|||
-- Iterates files in given directory |
|||
local function files(directory, recursively) |
|||
-- Use windows" dir command |
|||
local directory = directory:gsub("/", "\\") |
|||
local filenames = getOutput(string.format("dir %s %s/B/A:A", directory, recursively and '/S' or '')) |
|||
-- Function to be called in "for filename in files(directory)" |
|||
return coroutine.wrap(function() |
|||
for filename in filenames:gmatch("([^\r\n]+)") do |
|||
coroutine.yield(filename) |
|||
end |
|||
end) |
|||
end |
|||
-- Walk "C:/Windows" looking for executables |
|||
local directory = "C:/Windows" |
|||
local pattern = ".*%.exe$" -- for finding executables |
|||
for filename in files(directory) do |
|||
if filename:match(pattern) then |
|||
print(filename) |
|||
end |
|||
end</syntaxhighlight> |
|||
=={{header|M2000 Interpreter}}== |
|||
Console has a popup list called Menu, which we can fill using Files statements. Files statement get some symbols before first argument for sorting and to not export to console but to menu list. So we can use MenuItems to find how many items return, and we can walk menu array to get the names (from 1 to MenuItems). |
|||
Files statement get as first argument a pattern or a list of file extensions "txt|bmp" return these two kind of files. |
|||
There is a second optional parameter which examine all files founded from first filter for included letters. We can add using | as seperator, a list of strings included in same line. Files examine all files, opened one by one, using an automatic way to find what kind of text file is, an Ansi, a Utf8, a Utf-16LE, or a Utf-16BE. Also automatic find the line breaks. All files converted at open as utf-16LE and then searched. For Ansi files, Locale used to make the right conversion. |
|||
<syntaxhighlight lang="m2000 interpreter"> |
|||
Module Show_Files_Standard { |
|||
\\ we get more (include hidden too) |
|||
Module InnerWay (folder_path$, pattern$){ |
|||
olddir$=dir$ |
|||
dir folder_path$ |
|||
\\ clear menu list |
|||
Menu |
|||
\\ + place export to menu, without showing |
|||
\\ ! sort to name |
|||
files ! + pattern$ |
|||
If MenuItems>0 then { |
|||
For i=1 to MenuItems { |
|||
Print Menu$(i)+".exe" |
|||
} |
|||
} |
|||
dir olddir$ |
|||
} |
|||
InnerWay "C:\Windows","*.exe" |
|||
} |
|||
Show_Files_Standard |
|||
</syntaxhighlight> |
|||
Like VbScript using external help, from a COM object. |
|||
We use an enumerator to iterate all file names and checked using like operator "~",and then we push them to end of stack (Data push to end), so we get first the first entered (we use stack here as a FIFO, using a New stack for temporary use), and we remove at the end all items and place them in an array. This array return from get_file$() and we make a second iterator for array, to get each end display it. The second iterator is not a com enumerator, but another type of object included in this interpreter. This iterator can get start and end position, defining a range and a direction too. |
|||
EnumFile is an object in an object. In expression we get the inner object. In While {} we get the outer object, and iterate or not (depends of state), so the inner object change. Because we get the first object at creation time, the first time when While structure found this object skips iteration. |
|||
Stack New {} make a block of a fresh stack of values, and at the exit attach the old stack (which for this block detached from execute object at the begin of block). |
|||
<syntaxhighlight lang="m2000 interpreter"> |
|||
Module Show_Files { |
|||
Function get_files$ (folder_path$) { |
|||
\\ we get second argument using letter$ which pop from stack |
|||
pattern$=lcase$(Letter$) |
|||
Declare objfso "Scripting.FileSystemObject" |
|||
Method objfso, "GetFolder", folder_path$ as fc |
|||
With fc, "files" set files |
|||
\\ from revision 13 - version 9.4 |
|||
With files, -4& as EnumFile |
|||
With EnumFile, "Name" as name$ |
|||
Dim empty$() |
|||
=empty$() |
|||
Stack New { |
|||
While EnumFile { |
|||
If lcase$(name$) ~ pattern$ Then Data name$ |
|||
} |
|||
\\ get stack values and fill an array |
|||
=Array$([]) |
|||
} |
|||
} |
|||
Dim Name$() |
|||
Name$()=get_files$("C:\Windows","*.exe") |
|||
m=each(Name$()) |
|||
While m { |
|||
Print Array$(m) |
|||
} |
|||
} |
|||
Show_Files |
|||
</syntaxhighlight> |
|||
=={{header|MACRO-10}}== |
|||
<syntaxhighlight lang="macro-10"> |
|||
TITLE DIRWLK - Directory Walker |
|||
SUBTTL PDP-10 Assembly Language (MACRO-10 @ TOPS-20). KJX 2022. |
|||
SEARCH MONSYM,MACSYM ;Get system-call names. |
|||
.REQUIRE SYS:MACREL ;Macros: TMSG, EJSHLT, etc. |
|||
STDAC. ;Define standard register names. |
|||
JFN: BLOCK 1 ;Space for JFN (file-handle) |
|||
FSPEC: BLOCK 20 ;Space for file specification. |
|||
FSPECL= <.-FSPEC>*5 ;Length in chars of file-spec. |
|||
GO:: RESET% ;Initialize process. |
|||
TMSG <Please enter filespec, wildcards are allowed: > |
|||
HRROI T1,FSPEC ;Read into FSPEC. |
|||
MOVEI T2,FSPECL ;Maximum allowed characters. |
|||
SETZ T3, ;No Ctrl-R prompting. |
|||
RDTTY% ;Read string from terminal. |
|||
EJSHLT ; Print error-msg on errors. |
|||
MOVX T1,GJ%OLD!GJ%IFG!GJ%FLG!GJ%SHT ;Various flags. |
|||
HRROI T2,FSPEC ;File specification from above. |
|||
GTJFN% ;Get JFN for first matching file. |
|||
EJSHLT ; Print error-msg on errors. |
|||
MOVEM T1,JFN ;Save JFN. |
|||
DO. |
|||
MOVEI T1,.PRIOU ;Write to standard-output. |
|||
HRRZ T2,JFN ;JFN from above to decode. |
|||
SETZ T3, ;No flags. |
|||
JFNS% ;Decode filename and print it. |
|||
EJSHLT ; Print error-msg on errors. |
|||
TMSG < |
|||
> ;Print newline. |
|||
MOVE T1,JFN ;Get JFN into T1. |
|||
GNJFN% ;Get next matching file. |
|||
JRST [ HALTF% ; Halt program on failure. |
|||
JRST GO ] |
|||
LOOP. ;No error: Do it again. |
|||
ENDDO. |
|||
END GO |
|||
</syntaxhighlight> |
|||
=={{header|Mathematica}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
The built-in function <code>FileNames</code> does exactly this: |
The built-in function <code>FileNames</code> does exactly this: |
||
:<code>FileNames[]</code> lists all files in the current working directory. |
:<code>FileNames[]</code> lists all files in the current working directory. |
||
Line 661: | Line 1,306: | ||
:<code>FileNames[forms,dirs,n]</code> includes files that are in subdirectories up to n levels down. |
:<code>FileNames[forms,dirs,n]</code> includes files that are in subdirectories up to n levels down. |
||
Examples (find all files in current directory, find all png files in root directory): |
Examples (find all files in current directory, find all png files in root directory): |
||
< |
<syntaxhighlight lang="mathematica">FileNames["*"] |
||
FileNames["*.png", $RootDirectory]</ |
FileNames["*.png", $RootDirectory]</syntaxhighlight> |
||
the result can be printed with Print /@ FileNames[....]. |
the result can be printed with Print /@ FileNames[....]. |
||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
< |
<syntaxhighlight lang="maxscript">getFiles "C:\\*.txt"</syntaxhighlight> |
||
=={{header|Nanoquery}}== |
|||
<syntaxhighlight lang="nanoquery">import Nanoquery.IO |
|||
for fname in new(File).listDir("/foo/bar") |
|||
if lower(new(File, fname).getExtension()) = ".mp3" |
|||
println filename |
|||
end |
|||
end</syntaxhighlight> |
|||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
< |
<syntaxhighlight lang="nemerle">using System.Console; |
||
using System.IO; |
using System.IO; |
||
Line 681: | Line 1,335: | ||
foreach (file in files) WriteLine(file); |
foreach (file in files) WriteLine(file); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref symbols nobinary |
options replace format comments java crossref symbols nobinary |
||
Line 718: | Line 1,372: | ||
return |
return |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 730: | Line 1,384: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
The “os” standard module provides several iterators to retrieve files or directories matching a pattern: <code>walkPattern</code> to retrieve files and directories, <code>walkFiles</code> to retrieve only files and <code>walkDirs</code> to retrieve only directories. The pattern is OS dependent but at least the <code>*.ext</code> notation is supported. |
|||
<lang nim>import os |
|||
And there is the powerful <code>walkDir</code> to list the content of a directory specified by its name (without pattern). |
|||
for file in walkFiles "/foo/bar/*.mp3": |
|||
Here is an example with <code>walkFiles</code> and a pattern: |
|||
echo file</lang> |
|||
<syntaxhighlight lang="nim">import os |
|||
=={{header|Objective-C}}== |
|||
<lang objc>NSString *dir = @"/foo/bar"; |
|||
for file in walkFiles "/foo/bar/*.mp3": |
|||
// Pre-OS X 10.5 |
|||
echo file</syntaxhighlight> |
|||
NSArray *contents = [[NSFileManager defaultManager] directoryContentsAtPath:dir]; |
|||
// OS X 10.5+ |
|||
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dir error:NULL]; |
|||
for (NSString *file in contents) |
|||
if ([[file pathExtension] isEqualToString:@"mp3"]) |
|||
NSLog(@"%@", file);</lang> |
|||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck">use IO; |
||
bundle Default { |
bundle Default { |
||
Line 761: | Line 1,408: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Objective-C}}== |
|||
<syntaxhighlight lang="objc">NSString *dir = @"/foo/bar"; |
|||
// Pre-OS X 10.5 |
|||
NSArray *contents = [[NSFileManager defaultManager] directoryContentsAtPath:dir]; |
|||
// OS X 10.5+ |
|||
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dir error:NULL]; |
|||
for (NSString *file in contents) |
|||
if ([[file pathExtension] isEqualToString:@"mp3"]) |
|||
NSLog(@"%@", file);</syntaxhighlight> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">#load "str.cma" |
||
let contents = Array.to_list (Sys.readdir ".") in |
let contents = Array.to_list (Sys.readdir ".") in |
||
let select pat str = Str.string_match (Str.regexp pat) str 0 in |
let select pat str = Str.string_match (Str.regexp pat) str 0 in |
||
List.filter (select ".*\\.jpg") contents</ |
List.filter (select ".*\\.jpg") contents</syntaxhighlight> |
||
=={{header|Odin}}== |
|||
<syntaxhighlight lang="odin">package main |
|||
import "core:fmt" |
|||
import "core:path/filepath" |
|||
main :: proc() { |
|||
matches, _err := filepath.glob("*.odin") |
|||
for match in matches do fmt.println(match) |
|||
}</syntaxhighlight> |
|||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
< |
<syntaxhighlight lang="oz">declare |
||
[Path] = {Module.link ['x-oz://system/os/Path.ozf']} |
[Path] = {Module.link ['x-oz://system/os/Path.ozf']} |
||
[Regex] = {Module.link ['x-oz://contrib/regex']} |
[Regex] = {Module.link ['x-oz://contrib/regex']} |
||
Line 778: | Line 1,448: | ||
MatchingFiles = {Filter Files fun {$ File} {Regex.search Pattern File} \= false end} |
MatchingFiles = {Filter Files fun {$ File} {Regex.search Pattern File} \= false end} |
||
in |
in |
||
{ForAll MatchingFiles System.showInfo}</ |
{ForAll MatchingFiles System.showInfo}</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
{{works with|Free Pascal}} |
{{works with|Free Pascal}} |
||
< |
<syntaxhighlight lang="pascal">{$H+} |
||
program Walk; |
program Walk; |
||
Line 812: | Line 1,482: | ||
end; |
end; |
||
FindClose(Res); |
FindClose(Res); |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">use 5.010; |
||
opendir my $dh, '/home/foo/bar'; |
|||
my $pattern = qr{ \A a }xmso; # match files whose first character is 'a' |
|||
say for grep { /php$/ } readdir $dh; |
|||
opendir my $dh, 'the_directory'; |
|||
closedir $dh;</syntaxhighlight> |
|||
say for grep { $pattern } readdir $dh; |
|||
closedir $dh;</lang> |
|||
Or using globbing, with the <code><></code> operator, |
Or using globbing, with the <code><></code> operator, |
||
< |
<syntaxhighlight lang="perl">use 5.010; say while </home/foo/bar/*.php>;</syntaxhighlight> |
||
Or the same with the builtin <code>glob()</code> function, |
Or the same with the builtin <code>glob()</code> function, |
||
< |
<syntaxhighlight lang="perl">my @filenames = glob('/home/foo/bar/*.php');</syntaxhighlight> |
||
The <code>glob()</code> function takes any expression for its pattern, whereas <code><></code> is only for a literal. |
The <code>glob()</code> function takes any expression for its pattern, whereas <code><></code> is only for a literal. |
||
< |
<syntaxhighlight lang="perl">my $pattern = '*.c'; |
||
my @filenames = glob($pattern);</ |
my @filenames = glob($pattern);</syntaxhighlight> |
||
=={{header| |
=={{header|Phix}}== |
||
{{libheader|Phix/basics}} |
|||
The <code>dir</code> function takes the directory to traverse, and optionally a named parameter <code>test</code>, which can for example be a regex: |
|||
The dir function accepts a DOS pattern, with some minor variations (eg "*" gets all files with no extension). |
|||
<lang perl6>.say for dir(".", :test(/foo/))</lang> |
|||
<!--<syntaxhighlight lang="phix">--> |
|||
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">columnize</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">dir</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"*.txt"</span><span style="color: #0000FF;">))[</span><span style="color: #000000;">D_NAME</span><span style="color: #0000FF;">],</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">))</span> |
|||
<!--</syntaxhighlight>--> |
|||
{{out}} |
|||
<pre> |
|||
copyright.txt |
|||
e-1millon.txt |
|||
ildump.txt |
|||
output.txt |
|||
readme.txt |
|||
_TODO.TXT |
|||
</pre> |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
{{works with|PHP|5.2.0}} |
{{works with|PHP|5.2.0}} |
||
< |
<syntaxhighlight lang="php">$pattern = 'php'; |
||
$dh = opendir('c:/foo/bar'); // Or '/home/foo/bar' for Linux |
$dh = opendir('c:/foo/bar'); // Or '/home/foo/bar' for Linux |
||
while (false !== ($file = readdir($dh))) |
while (false !== ($file = readdir($dh))) |
||
Line 846: | Line 1,527: | ||
} |
} |
||
} |
} |
||
closedir($dh);</ |
closedir($dh);</syntaxhighlight> |
||
Or: |
Or: |
||
< |
<syntaxhighlight lang="php">$pattern = 'php'; |
||
foreach (scandir('/home/foo/bar') as $file) |
foreach (scandir('/home/foo/bar') as $file) |
||
{ |
{ |
||
Line 858: | Line 1,539: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{works with|PHP|<nowiki>4 >= 4.3.0 or 5</nowiki>}} |
{{works with|PHP|<nowiki>4 >= 4.3.0 or 5</nowiki>}} |
||
< |
<syntaxhighlight lang="php">foreach (glob('/home/foo/bar/*.php') as $file){ |
||
echo "$file\n"; |
echo "$file\n"; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(for F (dir "@src/") # Iterate directory |
||
(when (match '`(chop "s@.c") (chop F)) # Matches 's*.c'? |
(when (match '`(chop "s@.c") (chop F)) # Matches 's*.c'? |
||
(println F) ) ) # Yes: Print it</ |
(println F) ) ) # Yes: Print it</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>"start.c" |
<pre>"start.c" |
||
Line 876: | Line 1,557: | ||
=={{header|Pike}}== |
=={{header|Pike}}== |
||
< |
<syntaxhighlight lang="pike">array(string) files = get_dir("/home/foo/bar"); |
||
foreach(files, string file) |
foreach(files, string file) |
||
write(file + "\n");</ |
write(file + "\n");</syntaxhighlight> |
||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
Built-in procedure sys_file_match searches directories (or directory trees) using shell-like patterns: |
Built-in procedure sys_file_match searches directories (or directory trees) using shell-like patterns: |
||
< |
<syntaxhighlight lang="pop11">lvars repp, fil; |
||
;;; create path repeater |
;;; create path repeater |
||
sys_file_match('*.p', '', false, 0) -> repp; |
sys_file_match('*.p', '', false, 0) -> repp; |
||
Line 889: | Line 1,570: | ||
;;; print the file |
;;; print the file |
||
printf(fil, '%s\n'); |
printf(fil, '%s\n'); |
||
endwhile;</ |
endwhile;</syntaxhighlight> |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
Since PowerShell is also a shell it should come as no surprise that this task is very simple. Listing the names of all text files, or the names of all files, starting with "f": |
Since PowerShell is also a shell it should come as no surprise that this task is very simple. Listing the names of all text files, or the names of all files, starting with "f": |
||
< |
<syntaxhighlight lang="powershell">Get-ChildItem *.txt -Name |
||
Get-ChildItem f* -Name</ |
Get-ChildItem f* -Name</syntaxhighlight> |
||
The <code>-Name</code> parameter tells the <code>Get-ChildItem</code> to return only the file names as string, otherwise a complete <code>FileInfo</code> or <code>DirectoryInfo</code> object would be returned, containing much more information than only the file name. |
The <code>-Name</code> parameter tells the <code>Get-ChildItem</code> to return only the file names as string, otherwise a complete <code>FileInfo</code> or <code>DirectoryInfo</code> object would be returned, containing much more information than only the file name. |
||
More complex matching can be accomplished by filtering the complete list of files using the <code>Where-Object</code> cmdlet. The following will output all file names that contain at least one vowel: |
More complex matching can be accomplished by filtering the complete list of files using the <code>Where-Object</code> cmdlet. The following will output all file names that contain at least one vowel: |
||
< |
<syntaxhighlight lang="powershell">Get-ChildItem -Name | Where-Object { $_ -match '[aeiou]' }</syntaxhighlight> |
||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
The match is made using DOS wildcards. It could easily be modified to match based on a regular expression if desired (i.e. using the PCRE library). |
The match is made using DOS wildcards. It could easily be modified to match based on a regular expression if desired (i.e. using the PCRE library). |
||
< |
<syntaxhighlight lang="purebasic">Procedure walkDirectory(directory.s = "", pattern.s = "") |
||
Protected directoryID |
Protected directoryID |
||
Line 920: | Line 1,601: | ||
Input() |
Input() |
||
CloseConsole() |
CloseConsole() |
||
EndIf</ |
EndIf</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
The [http://python.org/doc/lib/module-glob.html glob] library included with Python lists files matching shell-like patterns: |
The [http://python.org/doc/lib/module-glob.html glob] library included with Python lists files matching shell-like patterns: |
||
< |
<syntaxhighlight lang="python">import glob |
||
for filename in glob.glob('/foo/bar/*.mp3'): |
for filename in glob.glob('/foo/bar/*.mp3'): |
||
print |
print(filename)</syntaxhighlight> |
||
Or manually: |
Or manually: |
||
< |
<syntaxhighlight lang="python">import os |
||
for filename in os.listdir('/foo/bar'): |
for filename in os.listdir('/foo/bar'): |
||
if filename.endswith('.mp3'): |
if filename.endswith('.mp3'): |
||
print |
print(filename)</syntaxhighlight> |
||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="r">dir("/foo/bar", "mp3")</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
<syntaxhighlight lang="racket"> |
|||
<lang Racket> |
|||
-> (for ([f (directory-list "/tmp")] #:when (regexp-match? "\\.rkt$" f)) |
-> (for ([f (directory-list "/tmp")] #:when (regexp-match? "\\.rkt$" f)) |
||
(displayln f)) |
(displayln f)) |
||
... *.rkt files ... |
... *.rkt files ... |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header| |
=={{header|Raku}}== |
||
(formerly Perl 6) |
|||
<lang raven>'dir://.' open each as item |
|||
The <code>dir</code> function takes the directory to traverse, and optionally a named parameter <code>test</code>, which is [https://docs.raku.org/routine/$TILDE$TILDE smart-matched] against the basename of each file (so for example we can use a regex): |
|||
item m/\.txt$/ if "%(item)s\n" print</lang> |
|||
<syntaxhighlight lang="raku" line>.say for dir ".", :test(/foo/);</syntaxhighlight> |
|||
=={{header|Rascal}}== |
=={{header|Rascal}}== |
||
< |
<syntaxhighlight lang="rascal">import IO; |
||
public void Walk(loc a, str pattern){ |
public void Walk(loc a, str pattern){ |
||
for (entry <- listEntries(a)) |
for (entry <- listEntries(a)) |
||
endsWith(entry, pattern) ? println(entry); |
endsWith(entry, pattern) ? println(entry); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Raven}}== |
|||
<syntaxhighlight lang="raven">'dir://.' open each as item |
|||
item m/\.txt$/ if "%(item)s\n" print</syntaxhighlight> |
|||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
{{works with|Regina}} |
{{works with|Regina}} |
||
The following program was tested in a DOS window under Windows/XP and should work for all Microsoft Windows. |
The following program was tested in a DOS window under Windows/XP and should work for all Microsoft Windows. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program shows files in directory tree that match a given criteria*/ |
||
parse arg xdir; if xdir='' then xdir='\' /*Any DIR? Use default.*/ |
parse arg xdir; if xdir='' then xdir='\' /*Any DIR? Use default.*/ |
||
@.=0 /*default in case ADDRESS fails. */ |
@.=0 /*default in case ADDRESS fails. */ |
||
Line 974: | Line 1,660: | ||
do j=1 for #; say @.j; end /*show files that met criteria. */ |
do j=1 for #; say @.j; end /*show files that met criteria. */ |
||
exit @.0+rc /*stick a fork in it, we're done.*/</ |
exit @.0+rc /*stick a fork in it, we're done.*/</syntaxhighlight> |
||
=={{header|Ring}}== |
|||
<syntaxhighlight lang="ring"> |
|||
###--------------------------------------- |
|||
### Directory Tree Walk |
|||
### Look for FileType for Music and Video |
|||
fileType = [".avi", ".mp4", ".mpg", ".mkv", ".mp3", ".wmv" ] |
|||
dirList = [] |
|||
musicList = [] |
|||
###--------------------------------------- |
|||
### Main |
|||
###----------------------------------- |
|||
### Start at this directory |
|||
searchVideoMusic("C:\Users\Umberto\") |
|||
see nl +"Number of Music and Videos files: " +len(musicList) +nl +nl |
|||
see musicList |
|||
See nl +"Finished" +nl |
|||
###======================================= |
|||
### Search for Video and Music files |
|||
Func searchVideoMusic(startDir) |
|||
ChDir(startDir + "Music") ### <<<== add Music subpath C:\Users\Umberto\Music |
|||
listDir( CurrentDir() ) |
|||
ChDir(startDir + "Videos") ### <<<== add Videos subpath C:\Users\Umberto\Videos |
|||
listDir( CurrentDir() ) |
|||
for searchDir in dirList ### Search Directory List for Music and Videos files |
|||
listDir(searchDir) |
|||
next |
|||
###============================== |
|||
### Find Files in Directory |
|||
Func listDir(dirName) |
|||
ChDir(dirName) |
|||
Try |
|||
###------------------------------------- |
|||
### Get SubDirectories |
|||
myListSub = Dir( CurrentDir() ) |
|||
Catch |
|||
###------------------------------------- |
|||
### Error, Couldn't open the directory |
|||
See "ListDir Catch! " + CurrentDir() +" --- "+ cCatchError +nl |
|||
return |
|||
Done |
|||
for x in myListSub |
|||
if x[2] |
|||
thisDir = x[1] |
|||
if thisDir[1] = "." |
|||
### Do Nothing. Ignore dot.name |
|||
else |
|||
see nl +"Dir: " + CurrentDir() +"\"+ thisDir + nl |
|||
###---------------------------------------- |
|||
### Directory Walk add to directory list |
|||
Add( dirList, (CurrentDir() +"\"+ thisDir)) |
|||
ok |
|||
else |
|||
thisFile = x[1] |
|||
###------------------------------- |
|||
### Add Music or Video file type |
|||
for thisType in fileType |
|||
if ( substr(thisFile, thisType) ) ### <<<== Type of File from List |
|||
see " File: " + thisFile + nl |
|||
Add(musicList, (CurrentDir() +"\"+ thisFile)) |
|||
ok |
|||
next |
|||
ok |
|||
next |
|||
return |
|||
###=============================================== |
|||
</syntaxhighlight> |
|||
OUTPUT: |
|||
<pre> |
|||
Dir: C:\Users\Umberto\Music\Free YouTube Downloader |
|||
File: stock.mp3 |
|||
File: big_buck_bunny.mp4 |
|||
File: BowieNikolaTesla'ThePrestige'.mpg |
|||
File: BowieTesla'The Prestige'.wmv |
|||
File: Candyman.mp4 |
|||
Dir: C:\Users\Umberto\Videos\Captures |
|||
File: drop.avi |
|||
Dir: C:\Users\Umberto\Videos\Free YouTube Downloader |
|||
File: GaryUSBondsQuarterToThree.avi |
|||
Dir: C:\Users\Umberto\Videos\HitomiTanaka[MIDE-219] |
|||
File: Joe.Versus.The.Volcano[1990].avi |
|||
File: SampleTheMythSanWa2005.mkv |
|||
File: stock.mp3 |
|||
Dir: C:\Users\Umberto\Videos\The Prestige (2006) |
|||
File: BowieNikola'The Prestige'.mp4 |
|||
File: BowieTeslaThe PrestigeConverted.mpg |
|||
File: 027_3xplanet_MDYD-895.avi |
|||
File: 3.mpg |
|||
File: HitomiTanaka[MIDE-219].mp4 |
|||
File: MDYD-868.wmv |
|||
File: MIDE-253.mp4 |
|||
File: MIDE_280.mp4 |
|||
File: PPPD-432.avi |
|||
File: The.Prestige.2006.mkv |
|||
Number of Music and Videos files: 20 |
|||
C:\Users\Umberto\Music\stock.mp3 |
|||
C:\Users\Umberto\Videos\big_buck_bunny.mp4 |
|||
C:\Users\Umberto\Videos\BowieNikolaTesla'ThePrestige'.mpg |
|||
C:\Users\Umberto\Videos\BowieTesla'The Prestige'.wmv |
|||
C:\Users\Umberto\Videos\Candyman.mp4 |
|||
C:\Users\Umberto\Videos\drop.avi |
|||
C:\Users\Umberto\Videos\GaryUSBondsQuarterToThree.avi |
|||
C:\Users\Umberto\Videos\Joe.Versus.The.Volcano[1990].avi |
|||
C:\Users\Umberto\Videos\SampleTheMythSanWa2005.mkv |
|||
C:\Users\Umberto\Videos\stock.mp3 |
|||
C:\Users\Umberto\Videos\Free YouTube Downloader\BowieNikola'The Prestige'.mp4 |
|||
C:\Users\Umberto\Videos\Free YouTube Downloader\BowieTeslaThe PrestigeConverted.mpg |
|||
C:\Users\Umberto\Videos\HitomiTanaka[MIDE-219]\027_3xplanet_MDYD-895.avi |
|||
C:\Users\Umberto\Videos\HitomiTanaka[MIDE-219]\3.mpg |
|||
C:\Users\Umberto\Videos\HitomiTanaka[MIDE-219]\HitomiTanaka[MIDE-219].mp4 |
|||
C:\Users\Umberto\Videos\HitomiTanaka[MIDE-219]\MDYD-868.wmv |
|||
C:\Users\Umberto\Videos\HitomiTanaka[MIDE-219]\MIDE-253.mp4 |
|||
C:\Users\Umberto\Videos\HitomiTanaka[MIDE-219]\MIDE_280.mp4 |
|||
C:\Users\Umberto\Videos\HitomiTanaka[MIDE-219]\PPPD-432.avi |
|||
C:\Users\Umberto\Videos\The Prestige (2006)\The.Prestige.2006.mkv |
|||
Finished |
|||
</pre> |
|||
=={{header|RPL}}== |
|||
{{works with|Halcyon Calc|4.2.7}} |
|||
The very first instruction of this program <code>VARS</code> returns the list of all current files and subdirectories. The rest of the code retains the names that comply with the pattern given in input, and which are not directories. To do so, the program attempts to recall the contents of each object on the stack through <code>RCL</code>: if an error occurs, the object is then a directory and shall not be processed further. |
|||
≪ VARS → filter list |
|||
≪ { } 1 list SIZE '''FOR''' j |
|||
list j GET |
|||
'''IFERR''' DUP RCL '''THEN''' DROP2 |
|||
'''ELSE''' |
|||
DROP →STR 2 OVER SIZE 1 - SUB |
|||
'''IF''' DUP filter POS '''THEN''' + ELSE DROP '''END''' |
|||
'''END''' |
|||
'''NEXT''' |
|||
≫ ≫ |
|||
'WKDIR' STO |
|||
"T" WKDIR |
|||
{{out}} |
|||
<pre> |
|||
1: { "T" "TESTPGM" "FACTN" } |
|||
</pre> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby"># Files under this directory: |
||
Dir.glob('*') { |file| puts file } |
Dir.glob('*') { |file| puts file } |
||
Line 988: | Line 1,849: | ||
puts file if file =~ pattern |
puts file if file =~ pattern |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Run BASIC}}== |
|||
<syntaxhighlight lang="runbasic">files #g, DefaultDir$ + "\*.jpg" ' find all jpg files |
|||
if #g HASANSWER() then |
|||
count = #g rowcount() ' get count of files |
|||
for i = 1 to count |
|||
if #g hasanswer() then 'retrieve info for next file |
|||
#g nextfile$() 'print name of file |
|||
print #g NAME$() |
|||
end if |
|||
next |
|||
end if |
|||
wait</syntaxhighlight> |
|||
FILE ACCESSOR methods |
|||
#handle HASANSWER() - Return non-zero if the file accessor has at least one resulting row. |
|||
#handle ROWCOUNT() - Return the number of rows returned. |
|||
#handle NEXTFILE$() - Advance to the next row and return a comma delimited string for the next file (name, size, date, time, directory flag). |
|||
#handle NEXTFILE$([delimExpr$]) - Like NEXTFILE$() but you get to specify the delimiter instead of a comma. |
|||
#handle NAME$() - Return the name of the current file row. |
|||
#handle SIZE() - Return the size of the current file row. |
|||
#handle DATE$() - Return a string containing a formatted date for the current file row. |
|||
#handle TIME$() - Return a string containing a formatted time for the current file row. |
|||
#handle ISDIR() - Return non-zero if the current file row represents a directory instead of a file. |
|||
#handle RESET() - Reset the file accessor back to the beginning so you can read through them again. |
|||
#handle DATEFORMAT(template$) - Set the date format using a "mmm dd, yyyy" style template$. |
|||
#handle TIMEFORMAT(template$) - Set the time format using a "hh:mm:ss" style template$. |
|||
#handle ISNULL() - Returns zero (or false) |
|||
#handle DEBUG$() - Returns the string "Files" |
|||
OUTPUT: |
|||
<pre> |
|||
button.JPG |
|||
circuitbanner1.JPG |
|||
circuitbanner2.JPG |
|||
copy.jpg |
|||
homecomputerbanner1.JPG |
|||
mandelbrot.jpg</pre> |
|||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">extern crate docopt; |
||
extern crate regex; |
extern crate regex; |
||
extern crate rustc_serialize; |
extern crate rustc_serialize; |
||
Line 1,026: | Line 1,926: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">import java.io.File |
||
val dir = new File("/foo/bar").list() |
val dir = new File("/foo/bar").list() |
||
dir.filter(file => file.endsWith(".mp3")).foreach(println)</ |
dir.filter(file => file.endsWith(".mp3")).foreach(println)</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
include "osfiles.s7i"; |
include "osfiles.s7i"; |
||
Line 1,047: | Line 1,947: | ||
end if; |
end if; |
||
end for; |
end for; |
||
end func;</ |
end func;</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">'*.p[lm]'.glob.each { |file| say file } # Perl files under this directory</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,057: | Line 1,957: | ||
</pre> |
</pre> |
||
<lang |
<syntaxhighlight lang="ruby">func file_match(Block callback, pattern=/\.txt\z/, path=Dir.cwd) { |
||
path.open(\var dir_h) || return |
path.open(\var dir_h) || return nil |
||
dir_h.entries.each { |entry| |
dir_h.entries.each { |entry| |
||
if (entry.basename ~~ pattern) { |
if (entry.basename ~~ pattern) { |
||
callback(entry) |
callback(entry) |
||
} |
} |
||
} |
} |
||
} |
} |
||
file_match( |
file_match( |
||
path: %d'/tmp', |
path: %d'/tmp', |
||
Line 1,072: | Line 1,972: | ||
say file; |
say file; |
||
} |
} |
||
)</syntaxhighlight> |
|||
);</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,080: | Line 1,980: | ||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
< |
<syntaxhighlight lang="smalltalk">(Directory name: 'a_directory') |
||
allFilesMatching: '*.st' do: [ :f | (f name) displayNl ]</ |
allFilesMatching: '*.st' do: [ :f | (f name) displayNl ]</syntaxhighlight> |
||
=={{header|Standard ML}}== |
|||
<syntaxhighlight lang="sml">fun dirEntries path = |
|||
let |
|||
fun loop strm = |
|||
case OS.FileSys.readDir strm of |
|||
SOME name => name :: loop strm |
|||
| NONE => [] |
|||
val strm = OS.FileSys.openDir path |
|||
in |
|||
loop strm before OS.FileSys.closeDir strm |
|||
end</syntaxhighlight> |
|||
List all "hidden" files (starting with a dot in Unix) in the current directory: |
|||
<syntaxhighlight lang="sml">(print o concat o map (fn s => s ^ "\n") o List.filter (String.isPrefix ".") o dirEntries) "."</syntaxhighlight> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
For the current directory: |
For the current directory: |
||
< |
<syntaxhighlight lang="tcl">foreach filename [glob *.txt] { |
||
puts $filename |
puts $filename |
||
}</ |
}</syntaxhighlight> |
||
For an arbitrary directory: |
For an arbitrary directory: |
||
< |
<syntaxhighlight lang="tcl">set dir /foo/bar |
||
foreach filename [glob -directory $dir *.txt] { |
foreach filename [glob -directory $dir *.txt] { |
||
puts $filename |
puts $filename |
||
### Or, if you only want the local filename part... |
### Or, if you only want the local filename part... |
||
# puts [file tail $filename] |
# puts [file tail $filename] |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Toka}}== |
=={{header|Toka}}== |
||
As with the C example, this uses a a POSIX extended regular expression as the pattern. The '''dir.listByPattern''' function used here was introduced in library revision 1.3. |
As with the C example, this uses a a POSIX extended regular expression as the pattern. The '''dir.listByPattern''' function used here was introduced in library revision 1.3. |
||
< |
<syntaxhighlight lang="toka">needs shell |
||
" ." " .\\.txt$" dir.listByPattern</ |
" ." " .\\.txt$" dir.listByPattern</syntaxhighlight> |
||
=={{header|TUSCRIPT}}== |
=={{header|TUSCRIPT}}== |
||
< |
<syntaxhighlight lang="tuscript">$$ MODE TUSCRIPT |
||
files=FILE_NAMES (+,-std-) |
files=FILE_NAMES (+,-std-) |
||
fileswtxt= FILTER_INDEX (files,":*.txt:",-) |
fileswtxt= FILTER_INDEX (files,":*.txt:",-) |
||
txtfiles= SELECT (files,#fileswtxt)</ |
txtfiles= SELECT (files,#fileswtxt)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,112: | Line 2,026: | ||
txtfiles ROSETTA.TXT |
txtfiles ROSETTA.TXT |
||
</pre> |
</pre> |
||
=={{header|TXR}}== |
|||
==== Using <code>glob</code> ==== |
|||
<syntaxhighlight lang="txrlisp">(glob "/etc/*.conf")</syntaxhighlight> |
|||
{{out}} |
|||
<syntaxhighlight lang="txrlisp">("/etc/adduser.conf" "/etc/apg.conf" "/etc/blkid.conf" "/etc/brltty.conf" |
|||
"/etc/ca-certificates.conf" "/etc/colord.conf" "/etc/ddclient.conf" |
|||
"/etc/debconf.conf" "/etc/deluser.conf" "/etc/dnsmasq.conf" "/etc/ffserver.conf" |
|||
"/etc/fuse.conf" "/etc/gai.conf" "/etc/hdparm.conf" "/etc/host.conf" |
|||
"/etc/insserv.conf" "/etc/irssi.conf" "/etc/kernel-img.conf" |
|||
"/etc/kerneloops.conf" "/etc/knockd.conf" "/etc/ld.so.conf" "/etc/lftp.conf" |
|||
"/etc/logrotate.conf" "/etc/ltrace.conf" "/etc/mke2fs.conf" "/etc/mtools.conf" |
|||
"/etc/netscsid.conf" "/etc/nsswitch.conf" "/etc/ntp.conf" "/etc/pam.conf" |
|||
"/etc/pnm2ppa.conf" "/etc/popularity-contest.conf" "/etc/resolv.conf" |
|||
"/etc/rsyslog.conf" "/etc/sensors3.conf" "/etc/sysctl.conf" "/etc/ucf.conf" |
|||
"/etc/updatedb.conf" "/etc/usb_modeswitch.conf" "/etc/wodim.conf")</syntaxhighlight> |
|||
==== Using <code>open-directory</code> and <code>get-lines</code> ==== |
|||
<syntaxhighlight lang="txrlisp">(mappend [iff (op ends-with ".conf") list] (get-lines (open-directory "/etc")))</syntaxhighlight> |
|||
{{out}} |
|||
<syntaxhighlight lang="txrlisp">("ddclient.conf" "gai.conf" "ucf.conf" "kernel-img.conf" "ltrace.conf" |
|||
"debconf.conf" "apg.conf" "adduser.conf" "mke2fs.conf" "colord.conf" |
|||
"kerneloops.conf" "fuse.conf" "hdparm.conf" "irssi.conf" "host.conf" |
|||
"ffserver.conf" "pam.conf" "sysctl.conf" "ld.so.conf" "dnsmasq.conf" |
|||
"insserv.conf" "brltty.conf" "deluser.conf" "netscsid.conf" "nsswitch.conf" |
|||
"mtools.conf" "wodim.conf" "updatedb.conf" "popularity-contest.conf" |
|||
"knockd.conf" "ntp.conf" "sensors3.conf" "resolv.conf" "blkid.conf" |
|||
"lftp.conf" "ca-certificates.conf" "usb_modeswitch.conf" "logrotate.conf" |
|||
"rsyslog.conf" "pnm2ppa.conf")</syntaxhighlight> |
|||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
< |
<syntaxhighlight lang="bash">ls -d *.c # *.c files in current directory |
||
(cd mydir && ls -d *.c) # *.c files in mydir</ |
(cd mydir && ls -d *.c) # *.c files in mydir</syntaxhighlight> |
||
<code>*.c</code> is a ''file name pattern'', also known as a ''glob pattern''. The shell expands each pattern to a sorted list of matching files. Details are in your shell's manual. |
<code>*.c</code> is a ''file name pattern'', also known as a ''glob pattern''. The shell expands each pattern to a sorted list of matching files. Details are in your shell's manual. |
||
Line 1,122: | Line 2,072: | ||
=={{header|UnixPipes}}== |
=={{header|UnixPipes}}== |
||
Here using grep for regexp. |
Here using grep for regexp. |
||
< |
<syntaxhighlight lang="bash">ls | grep '\.c$'</syntaxhighlight> |
||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
Sub show_files(folder_path,pattern) |
Sub show_files(folder_path,pattern) |
||
Set objfso = CreateObject("Scripting.FileSystemObject") |
Set objfso = CreateObject("Scripting.FileSystemObject") |
||
Line 1,136: | Line 2,086: | ||
Call show_files("C:\Windows",".exe") |
Call show_files("C:\Windows",".exe") |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Visual Basic .NET}}== |
=={{header|Visual Basic .NET}}== |
||
{{works with|Visual Basic .NET|9.0+}} |
{{works with|Visual Basic .NET|9.0+}} |
||
< |
<syntaxhighlight lang="vbnet">'Using the OS pattern matching |
||
For Each file In IO.Directory.GetFiles("\temp", "*.txt") |
For Each file In IO.Directory.GetFiles("\temp", "*.txt") |
||
Console.WriteLine(file) |
Console.WriteLine(file) |
||
Line 1,153: | Line 2,103: | ||
For Each file In IO.Directory.GetFiles("\temp").Where(Function(f) f Like "*.txt") |
For Each file In IO.Directory.GetFiles("\temp").Where(Function(f) f Like "*.txt") |
||
Console.WriteLine(file) |
Console.WriteLine(file) |
||
Next</ |
Next</syntaxhighlight> |
||
=={{header|Wren}}== |
|||
{{libheader|Wren-pattern}} |
|||
<syntaxhighlight lang="wren">import "io" for Directory |
|||
import "./pattern" for Pattern |
|||
var walk = Fn.new { |dir, pattern| |
|||
if (!Directory.exists(dir)) Fiber.abort("Directory does not exist.") |
|||
var files = Directory.list(dir) |
|||
return files.where { |f| pattern.isMatch(f) } |
|||
} |
|||
// get all C header files beginning with 'a' or 'b' |
|||
var p = Pattern.new("[a|b]+0^..h", Pattern.whole) |
|||
for (f in walk.call("/usr/include", p)) System.print(f)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
aio.h |
|||
aliases.h |
|||
alloca.h |
|||
ar.h |
|||
argp.h |
|||
argz.h |
|||
asoundlib.h |
|||
assert.h |
|||
byteswap.h |
|||
</pre> |
|||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
Unix glob, with wildcarding and options on file type, case folding and a few others. |
Unix glob, with wildcarding and options on file type, case folding and a few others. |
||
< |
<syntaxhighlight lang="zkl">File.glob("*.zkl") //--> list of matches</syntaxhighlight> |
||
=={{header|Zsh}}== |
=={{header|Zsh}}== |
||
Zsh has powerful filename generation features, which can filter by file names, permissions, size, type, etc. |
Zsh has powerful filename generation features, which can filter by file names, permissions, size, type, etc. |
||
< |
<syntaxhighlight lang="bash">print -l -- *.c</syntaxhighlight> |
||
{{omit from|AWK|Use a shell command: system("ls *.awk")}} |
{{omit from|AWK|Use a shell command: system("ls *.awk")}} |
||
Line 1,172: | Line 2,150: | ||
{{omit from|PARI/GP}} |
{{omit from|PARI/GP}} |
||
{{omit from|Retro}} |
{{omit from|Retro}} |
||
{{omit from|TI-83 BASIC|Does not have a filesystem, just namespaced variables, which can't be listed from a program.}} |
|||
{{omit from|TI-89 BASIC|Does not have a filesystem, just namespaced variables, which can't be listed from a program.}} |
{{omit from|TI-89 BASIC|Does not have a filesystem, just namespaced variables, which can't be listed from a program.}} |
||
{{omit from|Unlambda|Does not have file system support.}} |
{{omit from|Unlambda|Does not have file system support.}} |
Latest revision as of 11:31, 16 February 2024
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
- Related task
- Walk Directory Tree (read entire directory tree).
11l
L(filename) fs:list_dir(‘/foo/bar’)
I filename.ends_with(‘.mp3’)
print(filename)
68000 Assembly
Non-recursive directory walk in Motorola 68000 assembly language under AmigaOs 2.04+ by Thorham. Uses regular Amiga dos pattern matching.
;
; Non-recursive directory walk for Motorola 68000 under AmigaOs 2.04+ by Thorham
;
execBase equ 4
;
; from exec includes
;
_LVOOpenLibrary equ -552
_LVOCloseLibrary equ -414
_LVOAllocVec equ -684
_LVOFreeVec equ -690
MEMF_ANY equ 0
;
; from dos includes
;
_LVOVPrintf equ -954
_LVOExamine equ -102
_LVOExNext equ -108
_LVOLock equ -84
_LVOUnLock equ -90
_LVOParsePatternNoCase equ -966
_LVOMatchPatternNoCase equ -972
ACCESS_READ equ -2
rsset 0
fib_DiskKey rs.l 1
fib_DirEntryType rs.l 1
fib_FileName rs.b 108
fib_Protection rs.l 1
fib_EntryType rs.l 1
fib_Size rs.l 1
fib_NumBlocks rs.l 1
fib_DateStamp rs.b 12
fib_Comment rs.b 80
fib_OwnerUID rs.w 1
fib_OwnerGID rs.w 1
fib_Reserved rs.b 32
fib_SIZEOF rs.b 0
;
; main
;
start
move.l execBase,a6
; open dos.library
lea dosName,a1
moveq #37,d0
jsr _LVOOpenLibrary(a6)
move.l d0,dosBase
beq exit
; allocate memory for file info block
move.l #fib_SIZEOF,d0
move.l #MEMF_ANY,d1
jsr _LVOAllocVec(a6)
move.l d0,fib
beq exit
; get directory lock
move.l dosBase,a6
move.l #pathString,d1
move.l #ACCESS_READ,d2
jsr _LVOLock(a6)
move.l d0,lock
beq exit
; examine directory for ExNext
move.l lock,d1
move.l fib,d2
jsr _LVOExamine(a6)
tst.w d0
beq exit
; parse pattern string
move.l #patternString,d1
move.l #patternParsed,d2
move.l #sizeof_patternString*2+2,d3
jsr _LVOParsePatternNoCase(a6)
tst.l d0
blt exit
; get some pointers for use in the loop
lea printfArgs,a2
move.l fib,a3
lea fib_FileName(a3),a3
.loop
; get next directory entry
move.l lock,d1
move.l fib,d2
jsr _LVOExNext(a6)
tst.w d0
beq exit
; match pattern
move.l #patternParsed,d1
move.l a3,d2
jsr _LVOMatchPatternNoCase(a6)
; if match then print file name
tst.l d0
beq .nomatch
move.l a3,(a2)
move.l #formatString,d1
move.l #printfArgs,d2
jsr _LVOVPrintf(a6)
.nomatch
bra .loop
; cleanup and exit
exit
move.l dosBase,a6
move.l lock,d1
jsr _LVOUnLock(a6)
move.l execBase,a6
move.l fib,a1
tst.l a1
beq .l1
jsr _LVOFreeVec(a6)
.l1
move.l dosBase,a1
jsr _LVOCloseLibrary(a6)
rts
section data,data_p
;
; variables
;
dosBase
dc.l 0
lock
dc.l 0
fib
dc.l 0
printfArgs
dc.l 0
;
; strings
;
dosName
dc.b "dos.library",0
pathString
dc.b "ram:",0
formatString
dc.b "%s",10,0
patternString
dc.b "#?",0
patternString_end
sizeof_patternString=patternString_end-patternString
patternParsed
dcb.b sizeof_patternString*2+2
8080 Assembly
This program runs under CP/M, which was the commonly used OS on 8080 (and Z80)-based machines. The pattern used is the CP/M file pattern, which is the same as a DOS pattern: the filename, the extension, and an optional drive letter.
exit: equ 0 ; CP/M syscall to exit
puts: equ 9 ; CP/M syscall to print a string
sfirst: equ 17 ; 'Find First' CP/M syscall
snext: equ 18 ; 'Find Next' CP/M syscall
FCB: equ 5Ch ; Location of FCB for file given on command line
org 100h
lxi d,FCB ; CP/M parses the command line for us automatically
mvi c,sfirst; and prepares an FCB which we can pass to SFIRST
call 5 ; immediately.
lxi d,emsg ; If SFIRST returns an error, there is no file,
mvi c,puts ; so we should print an error message.
loop: inr a ; A=FF = error
jz 5
dcr a ; If we _do_ have a file, the directory entry
rrc ; is located at DTA (80h) + A * 32. 0<=A<=3.
rrc ; Rotate right twice, moving low bits into high bits,
stc ; then finally rotate a 1 bit into the top bit.
rar ; The effect is 000000AB -> 1AB00000.
inr a ; Finally the filename is at offset 1 in the dirent.
mvi h,0 ; Set HL = pointer to the filename
mov l,a
lxi d,fname ; The filename is stored as 'FILENAMEEXT', but let's
mvi b,8 ; be nice and print 'FILENAME.EXT\r\n'.
call memcpy ; Copy filename (wihtout extension) into placeholder
inx d ; Skip the '.' in the placeholder
mvi b,3 ; Then copy the extension
call memcpy
lxi d,fname ; Then print the formatted filename
mvi c,puts
call 5
lxi d,FCB ; Find the next file matching the pattern in the FCB
mvi c,snext ; The result is the same as for SFIRST, so we can
call 5 ; loop back here, except FF means no more files.
mvi c,exit ; Arrange for the error routine to instead exit cleanly
jmp loop
memcpy: mov a,m ; Copy B bytes from HL to DE
stax d
inx h
inx d
dcr b
jnz memcpy
ret
emsg: db 'Not Found$'
fname: db 'XXXXXXXX.XXX',13,10,'$' ; Filename placeholder
- Output:
I>dir I: TINST COM : TINST DTA : TINST MSG : TURBO COM I: TURBO MSG : TURBO OVR : WALKDIR ASM : WALKDIR PRN I: WALKDIR HEX : WALKDIR COM I>walkdir walkdir.* WALKDIR .ASM WALKDIR .PRN WALKDIR .HEX WALKDIR .COM I>walkdir *.com TINST .COM TURBO .COM WALKDIR .COM I>walkdir foobar.baz Not Found I>dir a:*.asm A: COUNT ASM : DETECT ASM : SUBLEQ ASM : LUHN ASM I>walkdir a:*.asm COUNT .ASM DETECT .ASM SUBLEQ .ASM LUHN .ASM
8th
"*.c" f:glob \ puts an array of strings with the file names on the top of the stack
Action!
The attached result has been obtained under DOS 2.5.
PROC GetFileName(CHAR ARRAY line,fname)
BYTE i,len
len=0
i=3
FOR i=3 TO 10
DO
IF line(i)=32 THEN EXIT FI
len==+1
fname(len)=line(i)
OD
len==+1
fname(len)='.
FOR i=11 TO 13
DO
IF line(i)=32 THEN EXIT FI
len==+1
fname(len)=line(i)
OD
fname(0)=len
RETURN
PROC Dir(CHAR ARRAY filter)
CHAR ARRAY line(255),fname(255)
BYTE dev=[1]
PrintE(filter)
Close(dev)
Open(dev,filter,6)
DO
InputSD(dev,line)
IF line(0)=0 OR line(0)>0 AND line(1)#32 THEN
EXIT
FI
GetFileName(line,fname)
Put(32) PrintE(fname)
OD
Close(dev)
PutE()
RETURN
PROC Main()
Dir("D:*.*")
Dir("H1:X*.*")
Dir("H1:?????.ACT")
Dir("H1:??F*.*")
RETURN
- Output:
Screenshot from Atari 8-bit computer
D:*.* DOS.SYS DUP.SYS INPUT.TXT H1:X*.* XIAOL_24.ACT XML_O_CU.ACT H1:?????.ACT AB_3D.ACT BREAK.ACT CUSIP.ACT SIEVE.ACT SLEEP.ACT WHILE.ACT H1:??F*.* HOFST_34.ACT INFINITE.ACT UTF8__P2.ACT
Ada
with Ada.Directories; use Ada.Directories;
with Ada.Text_IO; use Ada.Text_IO;
procedure Walk_Directory
(Directory : in String := ".";
Pattern : in String := "") -- empty pattern = all file names/subdirectory names
is
Search : Search_Type;
Dir_Ent : Directory_Entry_Type;
begin
Start_Search (Search, Directory, Pattern);
while More_Entries (Search) loop
Get_Next_Entry (Search, Dir_Ent);
Put_Line (Simple_Name (Dir_Ent));
end loop;
End_Search (Search);
end Walk_Directory;
ALGOL 68
INT match=0, no match=1, out of memory error=2, other error=3;
[]STRING directory = get directory(".");
FOR file index TO UPB directory DO
STRING file = directory[file index];
IF grep in string("[Ss]ort*.[.]a68$", file, NIL, NIL) = match THEN
print((file, new line))
FI
OD
- Sample output:
Quick_sort.a68 Shell_sort.a68 Cocktail_Sort.a68 Selection_Sort.a68 Merge_sort.a68 Bobosort.a68 Insertion_Sort.a68 Permutation_Sort.a68
AppleScript
AppleScript itself has limited built-in file system access. Typically, the Mac OS Finder is used to gather such information. To list all file/folders in the root directory:
tell application "Finder" to return name of every item in (startup disk)
--> EXAMPLE RESULT: {"Applications", "Developer", "Library", "System", "Users"}
To list all pdf files in user's home directory:
tell application "Finder" to return name of every item in (path to documents folder from user domain) whose name ends with "pdf"
--> EXAMPLE RESULT: {"About Stacks.pdf", "Test.pdf"}
The key clause is the whose
modifier keyword. The Finder can interpret many variations, including such terms as whose name begins with
, whose name contains
, etc. As well as boolean combinations:
tell application "Finder" to return name of every item in (path to documents folder from user domain) whose name does not contain "about" and name ends with "pdf"
--> RETURNS: {"Test.pdf"}
The Finder also supports the entire contents
modifier keyword, which effectively performs a recursive directory scan without recursion.
tell application "Finder" to return name of every item in entire contents of (path to documents folder from user domain) whose name ends with "pdf"
Nowadays, it's more usual to use macOS's System Events application for this kind of task as it's very much faster than the Finder, especially with 'whose' filters. However, its results, unlike the Finder's, aren't sorted by the items' names and it includes results for hidden items too if these match the criteria.
tell application "System Events" to return name of every item in documents folder whose name extension is "pdf"
--> EXAMPLE RESULT: {"ShellScripting.pdf", "RFC 4180 (CSV spec).pdf", "About Stacks.pdf", "AppleScriptLanguageGuide.pdf", "robinson_jeffers_2004_9.pdf", "DiskWarrior Manual.pdf", "RFC 2445 (iCalendar spec).pdf", "Artistic Orchestration.pdf"}
Intermediate in speed between the Finder and System Events are shell scripts, which are handy if you're more comfortable with shell scripts than with AppleScript.
set docsFolderPath to POSIX path of (path to documents folder)
-- By default, "ls" returns file names sorted by character code, so save the sorting until the end and do it case-insensitively.
set shellCommandText to "ls -f " & quoted form of docsFolderPath & " | grep -i '\\.pdf$' | sort -f"
return paragraphs of (do shell script shellCommandText)
--> EXAMPLE RESULT: {"About Stacks.pdf", "AppleScriptLanguageGuide.pdf", "Artistic Orchestration.pdf", "DiskWarrior Manual.pdf", "RFC 2445 (iCalendar spec).pdf", "RFC 4180 (CSV spec).pdf", "robinson_jeffers_2004_9.pdf", "ShellScripting.pdf"}
Best of all for speed and sorting, although requiring somewhat more code, are the Foundation methods available through AppleScriptObjC.
use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use scripting additions
set docsFolderURL to current application's class "NSURL"'s fileURLWithPath:(POSIX path of (path to documents folder))
-- Get NSURLs for the folder's visible contents.
tell current application's class "NSFileManager"'s defaultManager() to ¬
set visibleItems to its contentsOfDirectoryAtURL:(docsFolderURL) includingPropertiesForKeys:({}) ¬
options:(current application's NSDirectoryEnumerationSkipsHiddenFiles) |error|:(missing value)
-- Filter case-insensitively for those whose names have ".pdf" extensions.
set filter to current application's class "NSPredicate"'s predicateWithFormat:("pathExtension ==[c] 'pdf'")
set PDFs to visibleItems's filteredArrayUsingPredicate:(filter)
-- Get the names of any matching items.
set pdfNames to PDFs's valueForKey:("lastPathComponent")
-- Sort these case-insensitively and considering numerics.
set pdfNames to pdfNames's sortedArrayUsingSelector:("localizedStandardCompare:")
-- Return the result as an AppleScript list of text.
return pdfNames as list
--> EXAMPLE RESULT: {"About Stacks.pdf", "AppleScriptLanguageGuide.pdf", "Artistic Orchestration.pdf", "DiskWarrior Manual.pdf", "RFC 2445 (iCalendar spec).pdf", "RFC 4180 (CSV spec).pdf", "robinson_jeffers_2004_9.pdf", "ShellScripting.pdf"}
Arturo
; list all files at current path
print list "."
; get all files at given path
; and select only the ones we want
; just select the files with .md extension
select list "some/path"
=> [".md" = extract.extension]
; just select the files that contain "test"
select list "some/path"
=> [in? "test"]
AutoHotkey
Display all INI files in Windows directory.
Loop, %A_WinDir%\*.ini
out .= A_LoopFileName "`n"
MsgBox,% out
BaCon
This code will print all files in the current directory ".", separated by a newline symbol:
PRINT WALK$(".", 1, ".+", FALSE, NL$)
BASIC
(older versions don't have DIR$
)
DOS wildcards are rather underpowered when compared to... well... anything else.
DECLARE SUB show (pattern AS STRING)
show "*.*"
SUB show (pattern AS STRING)
DIM f AS STRING
f = DIR$(pattern)
DO WHILE LEN(f)
PRINT f
f = DIR$
LOOP
END SUB
BASIC256
call show ("c:\")
end
subroutine show (pattern$)
f$ = dir(pattern$)
while length(f$)
print f$
f$ = dir
end while
end subroutine
Batch File
A simple command that displays all EXE files in System32 directory non-recursively.
dir /b "%windir%\system32\*.exe"
The same command inside FOR loop:
- Inside a Batch File:
@for /F "tokens=*" %%F in ('dir /b "%windir%\system32\*.exe"') do echo %%F
- Command-line:
for /F "tokens=*" %F in ('dir /b "%windir%\system32\*.exe"') do echo %F
BBC BASIC
directory$ = "C:\Windows\"
pattern$ = "*.ini"
PROClistdir(directory$ + pattern$)
END
DEF PROClistdir(afsp$)
LOCAL dir%, sh%, res%
DIM dir% LOCAL 317
SYS "FindFirstFile", afsp$, dir% TO sh%
IF sh% <> -1 THEN
REPEAT
PRINT $$(dir%+44)
SYS "FindNextFile", sh%, dir% TO res%
UNTIL res% = 0
SYS "FindClose", sh%
ENDIF
ENDPROC
C
In this example, the pattern is a POSIX extended regular expression.
#include <sys/types.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_BADOPEN,
};
int walker(const char *dir, const char *pattern)
{
struct dirent *entry;
regex_t reg;
DIR *d;
if (regcomp(®, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
if (!(d = opendir(dir)))
return WALK_BADOPEN;
while (entry = readdir(d))
if (!regexec(®, entry->d_name, 0, NULL, 0))
puts(entry->d_name);
closedir(d);
regfree(®);
return WALK_OK;
}
int main()
{
walker(".", ".\\.c$");
return 0;
}
C#
using System;
using System.IO;
namespace DirectoryWalk
{
class Program
{
static void Main(string[] args)
{
string[] filePaths = Directory.GetFiles(@"c:\MyDir", "a*");
foreach (string filename in filePaths)
Console.WriteLine(filename);
}
}
}
C++
#include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
// list all files starting with a
boost::regex pattern("a.*");
for (directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
boost::smatch match;
std::string fn = iter->path().filename().string(); // must make local variable
if (boost::regex_match( fn, match, pattern))
{
std::cout << match[0] << "\n";
}
}
}
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
fs::path current_dir(".");
// list all files containing an mp3 extension
for (auto &file : fs::directory_iterator(current_dir)) {
if (file.path().extension() == ".mp3")
std::cout << file.path().filename().string() << std::endl;
}
}
Clojure
Using Java 8's PathMatcher patterns.
(import java.nio.file.FileSystems)
(defn match-files [f pattern]
(.matches (.getPathMatcher (FileSystems/getDefault) (str "glob:*" pattern)) (.toPath f)))
(defn walk-directory [dir pattern]
(let [directory (clojure.java.io/file dir)]
(map #(.getPath %) (filter #(match-files % pattern) (.listFiles directory)))))
ColdFusion
This example display all files and directories directly under C:\temp that end with .html
<cfdirectory action="list" directory="C:\temp" filter="*.html" name="dirListing">
<cfoutput query="dirListing">
#dirListing.name# (#dirListing.type#)<br>
</cfoutput>
Common Lisp
(defun walk-directory (directory pattern)
(directory (merge-pathnames pattern directory)))
Uses the filename pattern syntax provided by the CL implementation.
D
void main() {
import std.stdio, std.file;
dirEntries(".", "*.*", SpanMode.shallow).writeln;
}
DCL
* matches any number of characters & matches exactly any one character
$ loop:
$ f = f$search( p1 )
$ if f .eqs. "" then $ exit
$ write sys$output f
$ goto loop
- Output:
$ @walk_a_directory *.* USERS:[DAVID]A.A;1 USERS:[DAVID]B.B;1 USERS:[DAVID]GG.GG;1 USERS:[DAVID]WALK_A_DIRECTORY.COM;1 $ @walk_a_directory *.% USERS:[DAVID]A.A;1 USERS:[DAVID]B.B;1 $ @walk_a_directory *a*.* USERS:[DAVID]A.A;1 USERS:[DAVID]WALK_A_DIRECTORY.COM;1 $
Delphi
Hand-coded
See: Pascal
Using System.IOUtils
program Walk_a_directory;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.IOUtils;
var
Files: TArray<string>;
FileName, Directory: string;
begin
Directory := TDirectory.GetCurrentDirectory; // dir = '.', work to
Files := TDirectory.GetFiles(Directory, '*.*');
for FileName in Files do
begin
Writeln(FileName);
end;
Readln;
end.
- Output:
D:\Rosettacode\Walk_a_directory\Win32\Debug\Walk_a_directory.exe
E
def walkDirectory(directory, pattern) {
for name => file ? (name =~ rx`.*$pattern.*`) in directory {
println(name)
}
}
Example:
? walkDirectory(<file:~>, "bash_")
.bash_history
.bash_profile
.bash_profile~
Elena
ELENA 6.x:
import system'io;
import system'routines;
import extensions'routines;
public program()
{
var dir := Directory.assign("c:\MyDir");
dir.getFiles("a.*").forEach(printingLn);
}
Elixir
# current directory
IO.inspect File.ls!
dir = "/users/public"
IO.inspect File.ls!(dir)
- Output:
["check.exs", "e.bat", "foo", "input.txt", "test.beam", "test.exs", "test.txt"] ["Desktop", "desktop.ini", "Documents", "Downloads", "Favorites", "Libraries", "Music", "Pictures", "Recorded TV", "Videos"]
Emacs Lisp
directory-files
gives filenames in a given
directory, optionally restricted to those matching a regexp.
(directory-files "/some/dir/name"
nil ;; just the filenames, not full paths
"\\.c\\'" ;; regexp
t) ;; don't sort the filenames
;;=> ("foo.c" "bar.c" ...)
Erlang
Use builtin function filelib:fold_files/5
- Output:
8> filelib:fold_files( "/tmp", ".*", false, fun(File, Acc) -> [File|Acc] end, []). ["/tmp/.X0-lock","/tmp/.cron-check-4000-was-here", "/tmp/kerneloops.XyN0SP","/tmp/npicagwD7tf"] 9> filelib:fold_files( "/tmp", "k.*P", false, fun(File, Acc) -> [File|Acc] end, []). ["/tmp/kerneloops.XyN0SP"]
Euphoria
include file.e
procedure show(sequence pattern)
sequence f
f = dir(pattern)
for i = 1 to length(f) do
puts(1,f[i][D_NAME])
puts(1,'\n')
end for
end procedure
show("*.*")
F#
System.IO.Directory.GetFiles("c:\\temp", "*.xml")
|> Array.iter (printfn "%s")
Factor
Using unix globs. Also see the "directory." in basis/tools/files.factor.
USING: globs io io.directories kernel regexp sequences ;
IN: walk-directory-non-recursively
: print-files ( path pattern -- )
[ directory-files ] [ <glob> ] bi* [ matches? ] curry filter
[ print ] each ;
Ex:
( scratchpad ) "." "*.txt" print-files license.txt
Forth
Gforth's directory walking functions are tied to the POSIX dirent functions, used by the C langauge entry above. Forth doesn't have regex support, so a simple filter function is used instead.
defer ls-filter ( name len -- ? )
: ls-all 2drop true ;
: ls-visible drop c@ [char] . <> ;
: ls ( dir len -- )
open-dir throw ( dirid )
begin
dup pad 256 rot read-dir throw
while
pad over ls-filter if
cr pad swap type
else drop then
repeat
drop close-dir throw ;
\ only show C language source and header files (*.c *.h)
: c-file? ( str len -- ? )
dup 3 < if 2drop false exit then
+ 1- dup c@
dup [char] c <> swap [char] h <> and if drop false exit then
1- dup c@ [char] . <> if drop false exit then
drop true ;
' c-file? is ls-filter
s" ." ls
FreeBASIC
Sub show (pattern As String)
Dim As String f = Dir$(pattern)
While Len(f)
Print f
f = Dir$
Wend
End Sub
show "*.*"
Sleep
Frink
This prints the names of all of the files in the current directory that end with .frink
using a regular expression.
for f = select[files["."], {|f1| f1.getName[] =~ %r/\.frink$/}]
println[f.getName[]]
- Output:
UTMtest.frink mersennetest.frink piChudnovskyNew.frink showFonts.frink graphicalSieve.frink ...
FutureBasic
include "NSLog.incl"
void local fn EnumerateDirectoryAtURL( dirURL as CFURLRef )
NSDirectoryEnumerationOptions options = NSDirectoryEnumerationSkipsPackageDescendants + ¬
NSDirectoryEnumerationSkipsHiddenFiles + ¬
NSDirectoryEnumerationSkipsSubdirectoryDescendants
DirectoryEnumeratorRef enumerator = fn FileManagerEnumeratorAtURL( dirURL, NULL, options, NULL, NULL )
CFURLRef url = fn EnumeratorNextObject( enumerator )
while ( url )
if ( fn StringIsEqual( fn URLPathExtension( url ), @"fb" ) )
NSLog(@"%@",fn URLLastPathComponent( url ))
end if
url = fn EnumeratorNextObject( enumerator )
wend
end fn
fn EnumerateDirectoryAtURL( fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask ) )
HandleEvents
- Output:
ListFormatter.fb ObjectProperty1.fb Archimedean Spiral with Bezier Curve.fb FB3D.fb lenArray.fb Rosettacode Random Noise v04.fb AssociatedObject.fb
Gambas
Click this link to run this code
Public Sub Main()
Dim sTemp As String
For Each sTemp In Dir("/etc", "*.d")
Print sTemp
Next
End
Output:
profile.d rc1.d rc4.d rcS.d binfmt.d init.d rc5.d rc2.d
Go
package main
import (
"fmt"
"path/filepath"
)
func main() {
fmt.Println(filepath.Glob("*.go"))
}
Groovy
// *** print *.txt files in current directory
new File('.').eachFileMatch(~/.*\.txt/) {
println it
}
// *** print *.txt files in /foo/bar
new File('/foo/bar').eachFileMatch(~/.*\.txt/) {
println it
}
Hare
use fmt;
use glob;
export fn main() void = {
ls("/etc/*.conf");
};
fn ls(pattern: str) void = {
let gen = glob::glob(pattern, glob::flags::NONE);
defer glob::finish(&gen);
for (true) match (glob::next(&gen)) {
case void =>
break;
case glob::failure =>
continue;
case let s: str =>
fmt::printfln("{}", s)!;
};
};
Haskell
In this example, the pattern is a POSIX extended regular expression.
import System.Directory
import Text.Regex
import Data.Maybe
walk :: FilePath -> String -> IO ()
walk dir pattern = do
filenames <- getDirectoryContents dir
mapM_ putStrLn $ filter (isJust.(matchRegex $ mkRegex pattern)) filenames
main = walk "." ".\\.hs$"
HicEst
CHARACTER dirtxt='dir.txt', filename*80
SYSTEM(DIR='*.*', FIle=dirtxt) ! "file names", length, attrib, Created, LastWrite, LastAccess
OPEN(FIle=dirtxt, Format='"",', LENgth=files) ! parses column 1 ("file names")
DO nr = 1, files
filename = dirtxt(nr,1) ! reads dirtxt row = nr, column = 1 to filename
! write file names with extensions "txt", or "hic", or "jpg" (case insensitive) using RegEx option =128:
IF( INDEX(filename, "\.txt|\.hic|\.jpg", 128) ) WRITE() filename
ENDDO
Icon and Unicon
This uses Unicon extensions for stat and to read directories. Icon can uses system to accomplish the same objective.
IDL
f = file_search('*.txt', count=cc)
if cc gt 0 then print,f
(IDL is an array language - very few things are ever done in 'loops'.)
J
require 'dir'
0 dir '*.png'
0 dir '/mydir/*.txt'
The verb dir supports a number of reporting options determined by its left argument. A left argument of 0 reports just the file names.
Java
File dir = new File("/foo/bar");
String[] contents = dir.list();
for (String file : contents)
if (file.endsWith(".mp3"))
System.out.println(file);
JavaScript
var fso = new ActiveXObject("Scripting.FileSystemObject");
var dir = fso.GetFolder('test_folder');
function walkDirectory(dir, re_pattern) {
WScript.Echo("Files in " + dir.name + " matching '" + re_pattern +"':");
walkDirectoryFilter(dir.Files, re_pattern);
WScript.Echo("Folders in " + dir.name + " matching '" + re_pattern +"':");
walkDirectoryFilter(dir.Subfolders, re_pattern);
}
function walkDirectoryFilter(items, re_pattern) {
var e = new Enumerator(items);
while (! e.atEnd()) {
var item = e.item();
if (item.name.match(re_pattern))
WScript.Echo(item.name);
e.moveNext();
}
}
walkDirectory(dir, '\\.txt$');
Julia
for filename in readdir("/foo/bar")
if endswith(filename, ".mp3")
print(filename)
end
end
Kotlin
// version 1.1.2
import java.io.File
fun walkDirectory(dirPath: String, pattern: Regex): List<String> {
val d = File(dirPath)
require(d.exists() && d.isDirectory())
return d.list().filter { it.matches(pattern) }
}
fun main(args: Array<String>) {
val r = Regex("""^a.*\.h$""") // get all C header files beginning with 'a'
val files = walkDirectory("/usr/include", r)
for (file in files) println(file)
}
Sample output (Ubuntu v14.04):
- Output:
argp.h alloca.h ar.h aliases.h autosprintf.h aio.h assert.h argz.h
Lasso
local(matchingfilenames = array)
dir('.') -> foreach => {#1 >> 'string' ? #matchingfilenames -> insert(#1)}
#matchingfilenames
-> array(mystrings.html, a_string_file.txt)
Lingo
-- Usage: printFiles("C:\scripts", ".ls")
on printFiles (dir, fileType)
i = 1
sub = fileType.length -1
repeat while TRUE
fn = getNthFileNameInFolder(dir, i)
if fn = EMPTY then exit repeat
i = i+1
if fn.length<fileType.length then next repeat
if fn.char[fn.length-sub..fn.length]=fileType then put fn
end repeat
end
LiveCode
set the defaultFolder to the documents folder -- the documents folder is a "specialFolderPath"
put the files into docfiles
filter docfiles with "*.txt"
put docfiles
Lua
Lua itself is extremely spartanic as it is meant for embedding. Reading out a directory is not something that a minimal standard C library can do, and so minimal Lua without native extension libraries can't do it either. But lfs (LuaFileSystem) is about as standard an extension as it gets, so we use that.
require "lfs"
directorypath = "." -- current working directory
for filename in lfs.dir(directorypath) do
if filename:match("%.lua$") then -- "%." is an escaped ".", "$" is end of string
print(filename)
end
end
Although Lua is spartanic, it still provides functions such as os.execute([command]) and io.popen(prog [, mode]). Below an example for Windows users having io.popen at their disposal. Mind you, it may pop-up a command window.
-- Gets the output of given program as string
-- Note that io.popen is not available on all platforms
local function getOutput(prog)
local file = assert(io.popen(prog, "r"))
local output = assert(file:read("*a"))
file:close()
return output
end
-- Iterates files in given directory
local function files(directory, recursively)
-- Use windows" dir command
local directory = directory:gsub("/", "\\")
local filenames = getOutput(string.format("dir %s %s/B/A:A", directory, recursively and '/S' or ''))
-- Function to be called in "for filename in files(directory)"
return coroutine.wrap(function()
for filename in filenames:gmatch("([^\r\n]+)") do
coroutine.yield(filename)
end
end)
end
-- Walk "C:/Windows" looking for executables
local directory = "C:/Windows"
local pattern = ".*%.exe$" -- for finding executables
for filename in files(directory) do
if filename:match(pattern) then
print(filename)
end
end
M2000 Interpreter
Console has a popup list called Menu, which we can fill using Files statements. Files statement get some symbols before first argument for sorting and to not export to console but to menu list. So we can use MenuItems to find how many items return, and we can walk menu array to get the names (from 1 to MenuItems).
Files statement get as first argument a pattern or a list of file extensions "txt|bmp" return these two kind of files. There is a second optional parameter which examine all files founded from first filter for included letters. We can add using | as seperator, a list of strings included in same line. Files examine all files, opened one by one, using an automatic way to find what kind of text file is, an Ansi, a Utf8, a Utf-16LE, or a Utf-16BE. Also automatic find the line breaks. All files converted at open as utf-16LE and then searched. For Ansi files, Locale used to make the right conversion.
Module Show_Files_Standard {
\\ we get more (include hidden too)
Module InnerWay (folder_path$, pattern$){
olddir$=dir$
dir folder_path$
\\ clear menu list
Menu
\\ + place export to menu, without showing
\\ ! sort to name
files ! + pattern$
If MenuItems>0 then {
For i=1 to MenuItems {
Print Menu$(i)+".exe"
}
}
dir olddir$
}
InnerWay "C:\Windows","*.exe"
}
Show_Files_Standard
Like VbScript using external help, from a COM object.
We use an enumerator to iterate all file names and checked using like operator "~",and then we push them to end of stack (Data push to end), so we get first the first entered (we use stack here as a FIFO, using a New stack for temporary use), and we remove at the end all items and place them in an array. This array return from get_file$() and we make a second iterator for array, to get each end display it. The second iterator is not a com enumerator, but another type of object included in this interpreter. This iterator can get start and end position, defining a range and a direction too.
EnumFile is an object in an object. In expression we get the inner object. In While {} we get the outer object, and iterate or not (depends of state), so the inner object change. Because we get the first object at creation time, the first time when While structure found this object skips iteration.
Stack New {} make a block of a fresh stack of values, and at the exit attach the old stack (which for this block detached from execute object at the begin of block).
Module Show_Files {
Function get_files$ (folder_path$) {
\\ we get second argument using letter$ which pop from stack
pattern$=lcase$(Letter$)
Declare objfso "Scripting.FileSystemObject"
Method objfso, "GetFolder", folder_path$ as fc
With fc, "files" set files
\\ from revision 13 - version 9.4
With files, -4& as EnumFile
With EnumFile, "Name" as name$
Dim empty$()
=empty$()
Stack New {
While EnumFile {
If lcase$(name$) ~ pattern$ Then Data name$
}
\\ get stack values and fill an array
=Array$([])
}
}
Dim Name$()
Name$()=get_files$("C:\Windows","*.exe")
m=each(Name$())
While m {
Print Array$(m)
}
}
Show_Files
MACRO-10
TITLE DIRWLK - Directory Walker
SUBTTL PDP-10 Assembly Language (MACRO-10 @ TOPS-20). KJX 2022.
SEARCH MONSYM,MACSYM ;Get system-call names.
.REQUIRE SYS:MACREL ;Macros: TMSG, EJSHLT, etc.
STDAC. ;Define standard register names.
JFN: BLOCK 1 ;Space for JFN (file-handle)
FSPEC: BLOCK 20 ;Space for file specification.
FSPECL= <.-FSPEC>*5 ;Length in chars of file-spec.
GO:: RESET% ;Initialize process.
TMSG <Please enter filespec, wildcards are allowed: >
HRROI T1,FSPEC ;Read into FSPEC.
MOVEI T2,FSPECL ;Maximum allowed characters.
SETZ T3, ;No Ctrl-R prompting.
RDTTY% ;Read string from terminal.
EJSHLT ; Print error-msg on errors.
MOVX T1,GJ%OLD!GJ%IFG!GJ%FLG!GJ%SHT ;Various flags.
HRROI T2,FSPEC ;File specification from above.
GTJFN% ;Get JFN for first matching file.
EJSHLT ; Print error-msg on errors.
MOVEM T1,JFN ;Save JFN.
DO.
MOVEI T1,.PRIOU ;Write to standard-output.
HRRZ T2,JFN ;JFN from above to decode.
SETZ T3, ;No flags.
JFNS% ;Decode filename and print it.
EJSHLT ; Print error-msg on errors.
TMSG <
> ;Print newline.
MOVE T1,JFN ;Get JFN into T1.
GNJFN% ;Get next matching file.
JRST [ HALTF% ; Halt program on failure.
JRST GO ]
LOOP. ;No error: Do it again.
ENDDO.
END GO
Mathematica/Wolfram Language
The built-in function FileNames
does exactly this:
FileNames[]
lists all files in the current working directory.FileNames[form]
lists all files in the current working directory whose names match the string pattern form.FileNames[{form1,form2,...}]
lists all files whose names match any of the form_i.FileNames[forms,{dir1,dir2,...}]
lists files with names matching forms in any of the directories dir_i.FileNames[forms,dirs,n]
includes files that are in subdirectories up to n levels down.
Examples (find all files in current directory, find all png files in root directory):
FileNames["*"]
FileNames["*.png", $RootDirectory]
the result can be printed with Print /@ FileNames[....].
MAXScript
getFiles "C:\\*.txt"
Nanoquery
import Nanoquery.IO
for fname in new(File).listDir("/foo/bar")
if lower(new(File, fname).getExtension()) = ".mp3"
println filename
end
end
Nemerle
using System.Console;
using System.IO;
module DirWalk
{
Main() : void
{
def files = Directory.GetFiles(@"C:\MyDir"); // retrieves only files
def files_subs = Directory.GetFileSystemEntries(@"C:\MyDir"); // also retrieves (but does not enter) sub-directories
// (like ls command)
foreach (file in files) WriteLine(file);
}
}
NetRexx
/* NetRexx */
options replace format comments java crossref symbols nobinary
import java.util.List
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method getFileNames(dirname, pattern) public static returns List
dir = File(dirname)
contents = dir.list()
fileNames = ArrayList()
loop fname over contents
if fname.matches(pattern) then do
fileNames.add(fname)
end
end fname
Collections.sort(fileNames)
return fileNames
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
parse arg dirname pattern
if dirname = '' then dirname = System.getProperty('user.dir')
if pattern = '' then pattern = '^RW.*\\.nrx$'
fileNames = getFileNames(dirname, pattern)
say 'Search of' dirname 'for files matching pattern "'pattern'" found' fileNames.size() 'files.'
loop fn = 0 while fn < fileNames.size()
say (fn + 1).right(5)':' fileNames.get(fn)
end fn
return
- Output:
Search of /Users/projects/RosettaCode/netrexx for files matching pattern "^RW.*\.nrx$" found 5 files. 1: RWalkDir_Iter.nrx 2: RWebScraping.nrx 3: RWindowCreate.nrx 4: RWriteFloatArray.nrx 5: RWriteName3D01.nrx
Nim
The “os” standard module provides several iterators to retrieve files or directories matching a pattern: walkPattern
to retrieve files and directories, walkFiles
to retrieve only files and walkDirs
to retrieve only directories. The pattern is OS dependent but at least the *.ext
notation is supported.
And there is the powerful walkDir
to list the content of a directory specified by its name (without pattern).
Here is an example with walkFiles
and a pattern:
import os
for file in walkFiles "/foo/bar/*.mp3":
echo file
Objeck
use IO;
bundle Default {
class Test {
function : Main(args : System.String[]) ~ Nil {
dir := Directory->List("/src/code");
for(i := 0; i < dir->Size(); i += 1;) {
if(dir[i]->EndsWith(".obs")) {
dir[i]->PrintLine();
};
};
}
}
}
Objective-C
NSString *dir = @"/foo/bar";
// Pre-OS X 10.5
NSArray *contents = [[NSFileManager defaultManager] directoryContentsAtPath:dir];
// OS X 10.5+
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dir error:NULL];
for (NSString *file in contents)
if ([[file pathExtension] isEqualToString:@"mp3"])
NSLog(@"%@", file);
OCaml
#load "str.cma"
let contents = Array.to_list (Sys.readdir ".") in
let select pat str = Str.string_match (Str.regexp pat) str 0 in
List.filter (select ".*\\.jpg") contents
Odin
package main
import "core:fmt"
import "core:path/filepath"
main :: proc() {
matches, _err := filepath.glob("*.odin")
for match in matches do fmt.println(match)
}
Oz
declare
[Path] = {Module.link ['x-oz://system/os/Path.ozf']}
[Regex] = {Module.link ['x-oz://contrib/regex']}
Files = {Filter {Path.readdir "."} Path.isFile}
Pattern = ".*\\.oz$"
MatchingFiles = {Filter Files fun {$ File} {Regex.search Pattern File} \= false end}
in
{ForAll MatchingFiles System.showInfo}
Pascal
{$H+}
program Walk;
uses SysUtils;
var Res: TSearchRec;
Pattern, Path, Name: String;
FileAttr: LongInt;
Attr: Integer;
begin
Write('File pattern: ');
ReadLn(Pattern); { For example .\*.pas }
Attr := faAnyFile;
if FindFirst(Pattern, Attr, Res) = 0 then
begin
Path := ExtractFileDir(Pattern);
repeat
Name := ConcatPaths([Path, Res.Name]);
FileAttr := FileGetAttr(Name);
if FileAttr and faDirectory = 0 then
begin
{ Do something with file name }
WriteLn(Name);
end
until FindNext(Res) <> 0;
end;
FindClose(Res);
end.
Perl
use 5.010;
opendir my $dh, '/home/foo/bar';
say for grep { /php$/ } readdir $dh;
closedir $dh;
Or using globbing, with the <>
operator,
use 5.010; say while </home/foo/bar/*.php>;
Or the same with the builtin glob()
function,
my @filenames = glob('/home/foo/bar/*.php');
The glob()
function takes any expression for its pattern, whereas <>
is only for a literal.
my $pattern = '*.c';
my @filenames = glob($pattern);
Phix
The dir function accepts a DOS pattern, with some minor variations (eg "*" gets all files with no extension).
puts(1,join(columnize(dir("*.txt"))[D_NAME],"\n"))
- Output:
copyright.txt e-1millon.txt ildump.txt output.txt readme.txt _TODO.TXT
PHP
$pattern = 'php';
$dh = opendir('c:/foo/bar'); // Or '/home/foo/bar' for Linux
while (false !== ($file = readdir($dh)))
{
if ($file != '.' and $file != '..')
{
if (preg_match("/$pattern/", $file))
{
echo "$file matches $pattern\n";
}
}
}
closedir($dh);
Or:
$pattern = 'php';
foreach (scandir('/home/foo/bar') as $file)
{
if ($file != '.' and $file != '..')
{
if (preg_match("/$pattern/", $file))
{
echo "$file matches $pattern\n";
}
}
}
foreach (glob('/home/foo/bar/*.php') as $file){
echo "$file\n";
}
PicoLisp
(for F (dir "@src/") # Iterate directory
(when (match '`(chop "s@.c") (chop F)) # Matches 's*.c'?
(println F) ) ) # Yes: Print it
- Output:
"start.c" "ssl.c" "subr.c" "sym.c" ...
Pike
array(string) files = get_dir("/home/foo/bar");
foreach(files, string file)
write(file + "\n");
Pop11
Built-in procedure sys_file_match searches directories (or directory trees) using shell-like patterns:
lvars repp, fil;
;;; create path repeater
sys_file_match('*.p', '', false, 0) -> repp;
;;; iterate over files
while (repp() ->> fil) /= termin do
;;; print the file
printf(fil, '%s\n');
endwhile;
PowerShell
Since PowerShell is also a shell it should come as no surprise that this task is very simple. Listing the names of all text files, or the names of all files, starting with "f":
Get-ChildItem *.txt -Name
Get-ChildItem f* -Name
The -Name
parameter tells the Get-ChildItem
to return only the file names as string, otherwise a complete FileInfo
or DirectoryInfo
object would be returned, containing much more information than only the file name.
More complex matching can be accomplished by filtering the complete list of files using the Where-Object
cmdlet. The following will output all file names that contain at least one vowel:
Get-ChildItem -Name | Where-Object { $_ -match '[aeiou]' }
PureBasic
The match is made using DOS wildcards. It could easily be modified to match based on a regular expression if desired (i.e. using the PCRE library).
Procedure walkDirectory(directory.s = "", pattern.s = "")
Protected directoryID
directoryID = ExamineDirectory(#PB_Any,directory,pattern)
If directoryID
While NextDirectoryEntry(directoryID)
PrintN(DirectoryEntryName(directoryID))
Wend
FinishDirectory(directoryID)
EndIf
EndProcedure
If OpenConsole()
walkDirectory()
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf
Python
The glob library included with Python lists files matching shell-like patterns:
import glob
for filename in glob.glob('/foo/bar/*.mp3'):
print(filename)
Or manually:
import os
for filename in os.listdir('/foo/bar'):
if filename.endswith('.mp3'):
print(filename)
R
dir("/foo/bar", "mp3")
Racket
-> (for ([f (directory-list "/tmp")] #:when (regexp-match? "\\.rkt$" f))
(displayln f))
... *.rkt files ...
Raku
(formerly Perl 6)
The dir
function takes the directory to traverse, and optionally a named parameter test
, which is smart-matched against the basename of each file (so for example we can use a regex):
.say for dir ".", :test(/foo/);
Rascal
import IO;
public void Walk(loc a, str pattern){
for (entry <- listEntries(a))
endsWith(entry, pattern) ? println(entry);
}
Raven
'dir://.' open each as item
item m/\.txt$/ if "%(item)s\n" print
REXX
The following program was tested in a DOS window under Windows/XP and should work for all Microsoft Windows.
/*REXX program shows files in directory tree that match a given criteria*/
parse arg xdir; if xdir='' then xdir='\' /*Any DIR? Use default.*/
@.=0 /*default in case ADDRESS fails. */
trace off /*suppress REXX err msg for fails*/
address system 'DIR' xdir '/b /s' with output stem @. /*issue DIR cmd.*/
if rc\==0 then do /*an error happened?*/
say '***error!*** from DIR' xDIR /*indicate que pasa.*/
say 'return code=' rc /*show the Ret Code.*/
exit rc /*exit with the RC.*/
end /* [↑] bad address.*/
#=@.rc /*number of entries.*/
if #==0 then #=' no ' /*use a word, ¬zero.*/
say center('directory ' xdir " has " # ' matching entries.',79,'─')
do j=1 for #; say @.j; end /*show files that met criteria. */
exit @.0+rc /*stick a fork in it, we're done.*/
Ring
###---------------------------------------
### Directory Tree Walk
### Look for FileType for Music and Video
fileType = [".avi", ".mp4", ".mpg", ".mkv", ".mp3", ".wmv" ]
dirList = []
musicList = []
###---------------------------------------
### Main
###-----------------------------------
### Start at this directory
searchVideoMusic("C:\Users\Umberto\")
see nl +"Number of Music and Videos files: " +len(musicList) +nl +nl
see musicList
See nl +"Finished" +nl
###=======================================
### Search for Video and Music files
Func searchVideoMusic(startDir)
ChDir(startDir + "Music") ### <<<== add Music subpath C:\Users\Umberto\Music
listDir( CurrentDir() )
ChDir(startDir + "Videos") ### <<<== add Videos subpath C:\Users\Umberto\Videos
listDir( CurrentDir() )
for searchDir in dirList ### Search Directory List for Music and Videos files
listDir(searchDir)
next
###==============================
### Find Files in Directory
Func listDir(dirName)
ChDir(dirName)
Try
###-------------------------------------
### Get SubDirectories
myListSub = Dir( CurrentDir() )
Catch
###-------------------------------------
### Error, Couldn't open the directory
See "ListDir Catch! " + CurrentDir() +" --- "+ cCatchError +nl
return
Done
for x in myListSub
if x[2]
thisDir = x[1]
if thisDir[1] = "."
### Do Nothing. Ignore dot.name
else
see nl +"Dir: " + CurrentDir() +"\"+ thisDir + nl
###----------------------------------------
### Directory Walk add to directory list
Add( dirList, (CurrentDir() +"\"+ thisDir))
ok
else
thisFile = x[1]
###-------------------------------
### Add Music or Video file type
for thisType in fileType
if ( substr(thisFile, thisType) ) ### <<<== Type of File from List
see " File: " + thisFile + nl
Add(musicList, (CurrentDir() +"\"+ thisFile))
ok
next
ok
next
return
###===============================================
OUTPUT:
Dir: C:\Users\Umberto\Music\Free YouTube Downloader File: stock.mp3 File: big_buck_bunny.mp4 File: BowieNikolaTesla'ThePrestige'.mpg File: BowieTesla'The Prestige'.wmv File: Candyman.mp4 Dir: C:\Users\Umberto\Videos\Captures File: drop.avi Dir: C:\Users\Umberto\Videos\Free YouTube Downloader File: GaryUSBondsQuarterToThree.avi Dir: C:\Users\Umberto\Videos\HitomiTanaka[MIDE-219] File: Joe.Versus.The.Volcano[1990].avi File: SampleTheMythSanWa2005.mkv File: stock.mp3 Dir: C:\Users\Umberto\Videos\The Prestige (2006) File: BowieNikola'The Prestige'.mp4 File: BowieTeslaThe PrestigeConverted.mpg File: 027_3xplanet_MDYD-895.avi File: 3.mpg File: HitomiTanaka[MIDE-219].mp4 File: MDYD-868.wmv File: MIDE-253.mp4 File: MIDE_280.mp4 File: PPPD-432.avi File: The.Prestige.2006.mkv Number of Music and Videos files: 20 C:\Users\Umberto\Music\stock.mp3 C:\Users\Umberto\Videos\big_buck_bunny.mp4 C:\Users\Umberto\Videos\BowieNikolaTesla'ThePrestige'.mpg C:\Users\Umberto\Videos\BowieTesla'The Prestige'.wmv C:\Users\Umberto\Videos\Candyman.mp4 C:\Users\Umberto\Videos\drop.avi C:\Users\Umberto\Videos\GaryUSBondsQuarterToThree.avi C:\Users\Umberto\Videos\Joe.Versus.The.Volcano[1990].avi C:\Users\Umberto\Videos\SampleTheMythSanWa2005.mkv C:\Users\Umberto\Videos\stock.mp3 C:\Users\Umberto\Videos\Free YouTube Downloader\BowieNikola'The Prestige'.mp4 C:\Users\Umberto\Videos\Free YouTube Downloader\BowieTeslaThe PrestigeConverted.mpg C:\Users\Umberto\Videos\HitomiTanaka[MIDE-219]\027_3xplanet_MDYD-895.avi C:\Users\Umberto\Videos\HitomiTanaka[MIDE-219]\3.mpg C:\Users\Umberto\Videos\HitomiTanaka[MIDE-219]\HitomiTanaka[MIDE-219].mp4 C:\Users\Umberto\Videos\HitomiTanaka[MIDE-219]\MDYD-868.wmv C:\Users\Umberto\Videos\HitomiTanaka[MIDE-219]\MIDE-253.mp4 C:\Users\Umberto\Videos\HitomiTanaka[MIDE-219]\MIDE_280.mp4 C:\Users\Umberto\Videos\HitomiTanaka[MIDE-219]\PPPD-432.avi C:\Users\Umberto\Videos\The Prestige (2006)\The.Prestige.2006.mkv Finished
RPL
The very first instruction of this program VARS
returns the list of all current files and subdirectories. The rest of the code retains the names that comply with the pattern given in input, and which are not directories. To do so, the program attempts to recall the contents of each object on the stack through RCL
: if an error occurs, the object is then a directory and shall not be processed further.
≪ VARS → filter list ≪ { } 1 list SIZE FOR j list j GET IFERR DUP RCL THEN DROP2 ELSE DROP →STR 2 OVER SIZE 1 - SUB IF DUP filter POS THEN + ELSE DROP END END NEXT ≫ ≫ 'WKDIR' STO
"T" WKDIR
- Output:
1: { "T" "TESTPGM" "FACTN" }
Ruby
# Files under this directory:
Dir.glob('*') { |file| puts file }
# Files under path '/foo/bar':
Dir.glob( File.join('/foo/bar', '*') ) { |file| puts file }
# As a method
def file_match(pattern=/\.txt/, path='.')
Dir[File.join(path,'*')].each do |file|
puts file if file =~ pattern
end
end
Run BASIC
files #g, DefaultDir$ + "\*.jpg" ' find all jpg files
if #g HASANSWER() then
count = #g rowcount() ' get count of files
for i = 1 to count
if #g hasanswer() then 'retrieve info for next file
#g nextfile$() 'print name of file
print #g NAME$()
end if
next
end if
wait
FILE ACCESSOR methods
- handle HASANSWER() - Return non-zero if the file accessor has at least one resulting row.
- handle ROWCOUNT() - Return the number of rows returned.
- handle NEXTFILE$() - Advance to the next row and return a comma delimited string for the next file (name, size, date, time, directory flag).
- handle NEXTFILE$([delimExpr$]) - Like NEXTFILE$() but you get to specify the delimiter instead of a comma.
- handle NAME$() - Return the name of the current file row.
- handle SIZE() - Return the size of the current file row.
- handle DATE$() - Return a string containing a formatted date for the current file row.
- handle TIME$() - Return a string containing a formatted time for the current file row.
- handle ISDIR() - Return non-zero if the current file row represents a directory instead of a file.
- handle RESET() - Reset the file accessor back to the beginning so you can read through them again.
- handle DATEFORMAT(template$) - Set the date format using a "mmm dd, yyyy" style template$.
- handle TIMEFORMAT(template$) - Set the time format using a "hh:mm:ss" style template$.
- handle ISNULL() - Returns zero (or false)
- handle DEBUG$() - Returns the string "Files"
OUTPUT:
button.JPG circuitbanner1.JPG circuitbanner2.JPG copy.jpg homecomputerbanner1.JPG mandelbrot.jpg
Rust
extern crate docopt;
extern crate regex;
extern crate rustc_serialize;
use docopt::Docopt;
use regex::Regex;
const USAGE: &'static str = "
Usage: rosetta <pattern>
Walks the directory tree starting with the current working directory and
print filenames matching <pattern>.
";
#[derive(Debug, RustcDecodable)]
struct Args {
arg_pattern: String,
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.decode())
.unwrap_or_else(|e| e.exit());
let re = Regex::new(&args.arg_pattern).unwrap();
let paths = std::fs::read_dir(".").unwrap();
for path in paths {
let path = path.unwrap().path();
let path = path.to_str().unwrap();
if re.is_match(path) {
println!("{}", path);
}
}
}
Scala
import java.io.File
val dir = new File("/foo/bar").list()
dir.filter(file => file.endsWith(".mp3")).foreach(println)
Seed7
$ include "seed7_05.s7i";
include "osfiles.s7i";
const proc: main is func
local
var string: fileName is "";
begin
for fileName range readDir(".") do
if endsWith(fileName, ".sd7") then
writeln(fileName);
end if;
end for;
end func;
Sidef
'*.p[lm]'.glob.each { |file| say file } # Perl files under this directory
- Output:
x.pl x.pm
func file_match(Block callback, pattern=/\.txt\z/, path=Dir.cwd) {
path.open(\var dir_h) || return nil
dir_h.entries.each { |entry|
if (entry.basename ~~ pattern) {
callback(entry)
}
}
}
file_match(
path: %d'/tmp',
pattern: /\.p[lm]\z/i,
callback: { |file|
say file;
}
)
- Output:
/tmp/x.pl /tmp/x.pm
Smalltalk
(Directory name: 'a_directory')
allFilesMatching: '*.st' do: [ :f | (f name) displayNl ]
Standard ML
fun dirEntries path =
let
fun loop strm =
case OS.FileSys.readDir strm of
SOME name => name :: loop strm
| NONE => []
val strm = OS.FileSys.openDir path
in
loop strm before OS.FileSys.closeDir strm
end
List all "hidden" files (starting with a dot in Unix) in the current directory:
(print o concat o map (fn s => s ^ "\n") o List.filter (String.isPrefix ".") o dirEntries) "."
Tcl
For the current directory:
foreach filename [glob *.txt] {
puts $filename
}
For an arbitrary directory:
set dir /foo/bar
foreach filename [glob -directory $dir *.txt] {
puts $filename
### Or, if you only want the local filename part...
# puts [file tail $filename]
}
Toka
As with the C example, this uses a a POSIX extended regular expression as the pattern. The dir.listByPattern function used here was introduced in library revision 1.3.
needs shell
" ." " .\\.txt$" dir.listByPattern
TUSCRIPT
$$ MODE TUSCRIPT
files=FILE_NAMES (+,-std-)
fileswtxt= FILTER_INDEX (files,":*.txt:",-)
txtfiles= SELECT (files,#fileswtxt)
- Output:
files DEST'MAKROS'ROSETTA.TXT'SKRIPTE'STUDENTS.XML'TUSTEP.INI fileswtxt 3 txtfiles ROSETTA.TXT
TXR
Using glob
(glob "/etc/*.conf")
- Output:
("/etc/adduser.conf" "/etc/apg.conf" "/etc/blkid.conf" "/etc/brltty.conf"
"/etc/ca-certificates.conf" "/etc/colord.conf" "/etc/ddclient.conf"
"/etc/debconf.conf" "/etc/deluser.conf" "/etc/dnsmasq.conf" "/etc/ffserver.conf"
"/etc/fuse.conf" "/etc/gai.conf" "/etc/hdparm.conf" "/etc/host.conf"
"/etc/insserv.conf" "/etc/irssi.conf" "/etc/kernel-img.conf"
"/etc/kerneloops.conf" "/etc/knockd.conf" "/etc/ld.so.conf" "/etc/lftp.conf"
"/etc/logrotate.conf" "/etc/ltrace.conf" "/etc/mke2fs.conf" "/etc/mtools.conf"
"/etc/netscsid.conf" "/etc/nsswitch.conf" "/etc/ntp.conf" "/etc/pam.conf"
"/etc/pnm2ppa.conf" "/etc/popularity-contest.conf" "/etc/resolv.conf"
"/etc/rsyslog.conf" "/etc/sensors3.conf" "/etc/sysctl.conf" "/etc/ucf.conf"
"/etc/updatedb.conf" "/etc/usb_modeswitch.conf" "/etc/wodim.conf")
Using open-directory
and get-lines
(mappend [iff (op ends-with ".conf") list] (get-lines (open-directory "/etc")))
- Output:
("ddclient.conf" "gai.conf" "ucf.conf" "kernel-img.conf" "ltrace.conf"
"debconf.conf" "apg.conf" "adduser.conf" "mke2fs.conf" "colord.conf"
"kerneloops.conf" "fuse.conf" "hdparm.conf" "irssi.conf" "host.conf"
"ffserver.conf" "pam.conf" "sysctl.conf" "ld.so.conf" "dnsmasq.conf"
"insserv.conf" "brltty.conf" "deluser.conf" "netscsid.conf" "nsswitch.conf"
"mtools.conf" "wodim.conf" "updatedb.conf" "popularity-contest.conf"
"knockd.conf" "ntp.conf" "sensors3.conf" "resolv.conf" "blkid.conf"
"lftp.conf" "ca-certificates.conf" "usb_modeswitch.conf" "logrotate.conf"
"rsyslog.conf" "pnm2ppa.conf")
UNIX Shell
ls -d *.c # *.c files in current directory
(cd mydir && ls -d *.c) # *.c files in mydir
*.c
is a file name pattern, also known as a glob pattern. The shell expands each pattern to a sorted list of matching files. Details are in your shell's manual.
If there are no *.c files, ls
fails with an error message.
UnixPipes
Here using grep for regexp.
ls | grep '\.c$'
VBScript
Sub show_files(folder_path,pattern)
Set objfso = CreateObject("Scripting.FileSystemObject")
For Each file In objfso.GetFolder(folder_path).Files
If InStr(file.Name,pattern) Then
WScript.StdOut.WriteLine file.Name
End If
Next
End Sub
Call show_files("C:\Windows",".exe")
Visual Basic .NET
'Using the OS pattern matching
For Each file In IO.Directory.GetFiles("\temp", "*.txt")
Console.WriteLine(file)
Next
'Using VB's pattern matching and LINQ
For Each file In (From name In IO.Directory.GetFiles("\temp") Where name Like "*.txt")
Console.WriteLine(file)
Next
'Using VB's pattern matching and dot-notation
For Each file In IO.Directory.GetFiles("\temp").Where(Function(f) f Like "*.txt")
Console.WriteLine(file)
Next
Wren
import "io" for Directory
import "./pattern" for Pattern
var walk = Fn.new { |dir, pattern|
if (!Directory.exists(dir)) Fiber.abort("Directory does not exist.")
var files = Directory.list(dir)
return files.where { |f| pattern.isMatch(f) }
}
// get all C header files beginning with 'a' or 'b'
var p = Pattern.new("[a|b]+0^..h", Pattern.whole)
for (f in walk.call("/usr/include", p)) System.print(f)
- Output:
aio.h aliases.h alloca.h ar.h argp.h argz.h asoundlib.h assert.h byteswap.h
zkl
Unix glob, with wildcarding and options on file type, case folding and a few others.
File.glob("*.zkl") //--> list of matches
Zsh
Zsh has powerful filename generation features, which can filter by file names, permissions, size, type, etc.
print -l -- *.c
- Programming Tasks
- File System Operations
- 11l
- 68000 Assembly
- 8080 Assembly
- 8th
- Action!
- Ada
- ALGOL 68
- AppleScript
- Arturo
- AutoHotkey
- BaCon
- BASIC
- BASIC256
- Batch File
- BBC BASIC
- C
- POSIX
- C sharp
- C++
- Boost
- Std
- Clojure
- ColdFusion
- Common Lisp
- D
- DCL
- Delphi
- System.IOUtils
- E
- Elena
- Elixir
- Emacs Lisp
- Erlang
- Euphoria
- F Sharp
- Factor
- Forth
- FreeBASIC
- Frink
- FutureBasic
- Gambas
- Go
- Groovy
- Hare
- Haskell
- HicEst
- Icon
- Unicon
- IDL
- J
- Java
- JavaScript
- Julia
- Kotlin
- Lasso
- Lingo
- LiveCode
- Lua
- M2000 Interpreter
- MACRO-10
- Mathematica
- Wolfram Language
- MAXScript
- Nanoquery
- Nemerle
- NetRexx
- Nim
- Objeck
- Objective-C
- OCaml
- Odin
- Oz
- Pascal
- Perl
- Phix
- Phix/basics
- PHP
- PicoLisp
- Pike
- Pop11
- PowerShell
- PureBasic
- Python
- R
- Racket
- Raku
- Rascal
- Raven
- REXX
- Ring
- RPL
- Ruby
- Run BASIC
- Rust
- Scala
- Seed7
- Sidef
- Smalltalk
- Standard ML
- Tcl
- Toka
- TUSCRIPT
- TXR
- UNIX Shell
- UnixPipes
- VBScript
- Visual Basic .NET
- Wren
- Wren-pattern
- Zkl
- Zsh
- AWK/Omit
- Bc/Omit
- Befunge/Omit
- Dc/Omit
- GUISS/Omit
- M4/Omit
- Make/Omit
- PARI/GP/Omit
- Retro/Omit
- TI-83 BASIC/Omit
- TI-89 BASIC/Omit
- Unlambda/Omit
- Axe/Omit