Walk a directory/Recursively: Difference between revisions

m
(Added a general comment.)
m (→‎{{header|Wren}}: Minor tidy)
 
(24 intermediate revisions by 11 users not shown)
Line 15:
*   [[Walk a directory/Non-recursively]]   (read a ''single directory'').
<br><br>
 
=={{header|11l}}==
{{trans|Nim}}
 
<syntaxhighlight lang="11l">L(filename) fs:walk_dir(‘/’)
I re:‘.*\.mp3’.match(filename)
print(filename)</syntaxhighlight>
 
=={{header|8th}}==
<langsyntaxhighlight lang="forth">
"*.c" f:rglob \ top of stack now has list of all "*.c" files, recursively
</syntaxhighlight>
</lang>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Directories; use Ada.Directories;
with Ada.Text_IO;
 
Line 45 ⟶ 52:
begin
Walk (".", "*.adb");
end Test_Directory_Walk;</langsyntaxhighlight>
The solution first enumerates files in a directory, that includes the subdirectories, if their names match the pattern. Then it steps down into each of the subdirectories. The pseudo directories . and .. are excluded. The behavior upon symbolic links depends on the [[OS]] and the implementation of the Ada.Directories package.
 
Line 52 ⟶ 59:
{{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}} -->
<langsyntaxhighlight lang="algol68">INT match=0, no match=1, out of memory error=2, other error=3;
 
STRING slash = "/", pwd=".", parent="..";
Line 78 ⟶ 85:
FI;
 
walk tree(".", match sort a68 and print)</langsyntaxhighlight>
{{out|Sample output}}
<pre>
Line 96 ⟶ 103:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">; list all files at current path
print list.recursive "."
 
Line 108 ⟶ 115:
; just select the files that contain "test"
select list.recursive "some/path"
=> [in? "test"]</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
Display all TMP files in Temp directory and its subdirectories.
<langsyntaxhighlight lang="autohotkey">Loop, %A_Temp%\*.tmp,,1
out .= A_LoopFileName "`n"
MsgBox,% out</langsyntaxhighlight>
 
=={{header|BaCon}}==
This line will recursively walk though all directories starting from the current directory ".":
<langsyntaxhighlight lang="qbasic">PRINT WALK$(".", 1, ".+", TRUE, NL$)</langsyntaxhighlight>
 
=={{header|Batch File}}==
A sample code that displays all the EXE files in System32 directory recursively.
<langsyntaxhighlight lang="dos">dir /s /b "%windir%\System32\*.exe"</langsyntaxhighlight>
----
If you wanted to apply some command to each item in a directory tree, then use <code>FOR</code> with the switch <code>/R</code>. For example, to apply the ECHO command to every DLL file in C:\Windows\System32:
{{works with|Windows NT|4 or later (includes Windows XP and onward)}}
<langsyntaxhighlight lang="dos">FOR /R C:\Windows\System32 %%F IN (*.DLL) DO ECHO "%%F"</langsyntaxhighlight>
This can be done from outside a batch file (entered directly at the command prompt) by changing the double percent signs (%%) to single percents (%):
<langsyntaxhighlight lang="dos">FOR /R C:\Windows\System32 %F IN (*.DLL) DO ECHO "%F"</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> directory$ = "C:\Windows\"
pattern$ = "*.chm"
PROClisttree(directory$, pattern$)
Line 159 ⟶ 166:
SYS "FindClose", sh%
ENDIF
ENDPROC</langsyntaxhighlight>
 
=={{header|C}}==
==={{libheader|POSIX}}===
{{works with|POSIX|.1-2001}}
<langsyntaxhighlight Clang="c">#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
Line 266 ⟶ 273:
}
return 0;
}</langsyntaxhighlight>
==={{libheader|BSD libc}}===
With the [http://www.openbsd.org/cgi-bin/man.cgi?query=fts&apropos=0&sektion=3&manpath=OpenBSD+Current&arch=i386&format=html fts(3)] functions from 4.4BSD, this program can sort the files, and can also detect cycles (when a link puts a directory inside itself). This program makes a ''logical traversal'' that follows symbolic links to directories.
{{works with|OpenBSD|4.9}}
<langsyntaxhighlight lang="c">#include <sys/types.h>
#include <err.h>
#include <errno.h>
Line 353 ⟶ 360:
pmatch(".", "*.c");
return 0;
}</langsyntaxhighlight>
=== [[Windows]] ===
{{libheader|Win32}}
{{works with|MinGW}}
<langsyntaxhighlight lang="c">#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
Line 594 ⟶ 601:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.IO;
Line 634 ⟶ 641:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
{{libheader|boost}}
<langsyntaxhighlight lang="cpp">#include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
Line 656 ⟶ 663:
std::cout << iter->path() << "\n";
}
}</langsyntaxhighlight>
 
{{libheader|std|C++17}}
<langsyntaxhighlight lang="cpp">
#include <filesystem>
#include <iostream>
Line 672 ⟶ 679:
std::cout << file.path().filename().string() << std::endl;
}
}</langsyntaxhighlight>
 
=={{header|Caché ObjectScript}}==
 
<langsyntaxhighlight lang="cos">
Class Utils.File [ Abstract ]
{
Line 699 ⟶ 706:
 
}
</syntaxhighlight>
</lang>
 
{{out|Example}}
Line 718 ⟶ 725:
=={{header|Clojure}}==
The standard function ''file-seq'' does a tree walk.
<langsyntaxhighlight lang="clojure">(use '[clojure.java.io])
 
(defn walk [dirpath pattern]
Line 725 ⟶ 732:
 
(map #(println (.getPath %)) (walk "src" #".*\.clj"))
</syntaxhighlight>
</lang>
 
=={{header|CoffeeScript}}==
{{works with|node.js}}
<langsyntaxhighlight lang="coffeescript">fs = require 'fs'
 
walk = (dir, f_match, f_visit) ->
Line 745 ⟶ 752:
matcher = (fn) -> fn.match /\.coffee/
action = console.log
walk dir, matcher, action</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
{{libheader|CL-FAD}}
This example uses the <code>CL-FAD</code> library to achieve compatibility where the ANSI CL standard leaves ambiguities about pathnames. Quicklisp is used to ensure it is loaded. Traversal is depth-first unless <code>:depth-first-p nil</code> is passed.
<langsyntaxhighlight lang="lisp">(ql:quickload :cl-fad)
(defun mapc-directory-tree (fn directory &key (depth-first-p t))
(dolist (entry (cl-fad:list-directory directory))
Line 759 ⟶ 766:
(when depth-first-p
(funcall fn entry))))
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight lang="lisp">CL-USER> (mapc-directory-tree (lambda (x)
(when (equal (pathname-type x) "lisp")
(write-line (namestring x))))
Line 770 ⟶ 777:
/home/sthalik/lang/lisp/box-muller.lisp
/home/sthalik/lang/lisp/displaced-subseq.lisp
[...]</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.file;
 
Line 779 ⟶ 786:
// a depth-first scan):
dirEntries("", "*.d", SpanMode.breadth).writeln;
}</langsyntaxhighlight>
 
=={{header|Dart}}==
<syntaxhighlight lang="dart">
import 'dart:io' show Directory, Platform, File;
 
void main(List<String> args) {
var dir = Directory(args[0]);
dir.list(recursive: true, followLinks: false).forEach((final cur) {
if (cur is Directory) {
print("Directory: ${cur.path}");
}
 
if (cur is File) {
print("File: ${cur.path}");
}
});
}
</syntaxhighlight>
 
=={{header|Delphi}}==
{{libheader| System.IOUtils}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Walk_a_directory;
 
Line 807 ⟶ 833:
end.
 
</syntaxhighlight>
</lang>
=={{header|E}}==
<langsyntaxhighlight lang="e">def walkTree(directory, pattern) {
for name => file in directory {
if (name =~ rx`.*$pattern.*`) {
Line 818 ⟶ 844:
}
}
}</langsyntaxhighlight>
{{out|Example}}
<langsyntaxhighlight lang="e">? walkTree(<file:/usr/share/man>, "rmdir")
/usr/share/man/man1/rmdir.1
/usr/share/man/man2/rmdir.2</langsyntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Walk_directory do
def recursive(dir \\ ".") do
Enum.each(File.ls!(dir), fn file ->
Line 834 ⟶ 860:
end
 
Walk_directory.recursive</langsyntaxhighlight>
 
{{out}}
Line 853 ⟶ 879:
 
=={{header|Emacs Lisp}}==
<langsyntaxhighlight lang="lisp">ELISP> (directory-files-recursively "/tmp/el" "\\.el$")
("/tmp/el/1/c.el" "/tmp/el/a.el" "/tmp/el/b.el")</langsyntaxhighlight>
 
=={{header|Erlang}}==
Line 860 ⟶ 886:
 
{{out}}
<langsyntaxhighlight lang="erlang">
walk_dir(Path, Pattern) ->
filelib:fold_files(
Line 869 ⟶ 895:
[]
)
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight lang="erlang">
% Collect every file in the current directory
walkdir:walk_dir(".", ".*").
Line 877 ⟶ 903:
% Collect every file my .config folder that ends with `rc`
walkdir:walk_dir("/home/me/.config/", ".*rc$").
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
This code is tail-recursive and lazy.
<langsyntaxhighlight lang="fsharp">open System.IO
 
let rec getAllFiles dir pattern =
Line 889 ⟶ 915:
 
getAllFiles "c:\\temp" "*.xml"
|> Seq.iter (printfn "%s")</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USE: io.directories.search
 
"." t [
dup ".factor" tail? [ print ] [ drop ] if
] each-file</langsyntaxhighlight>
 
=={{header|Forth}}==
{{works with|gforth|0.7.9}}
<langsyntaxhighlight lang="forth">
require unix/filestat.fs
require unix/libc.fs
Line 948 ⟶ 974:
 
s" ." ls-r cr
</syntaxhighlight>
</lang>
 
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">#include "dir.bi"
 
Sub listFiles(Byref filespec As String, Byval attrib As Integer)
Dim As Integer count = 0
Dim As String filename = Dir(filespec, attrib)
Do While Len(filename) > 0
count += 1
Print filename
filename = Dir()
Loop
Print !"\nArchives count:"; count
End Sub
 
Dim As String mylist = "C:\FreeBASIC\""
Print "Directories:"
listFiles(mylist & "*", fbDirectory)
Print
Print "Archive files:"
listFiles(mylist & "*", fbArchive)
Sleep</syntaxhighlight>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
void local fn EnumerateDirectoryAtURL( dirURL as CFURLRef )
NSDirectoryEnumerationOptions options = NSDirectoryEnumerationSkipsPackageDescendants + ¬
NSDirectoryEnumerationSkipsHiddenFiles
DirectoryEnumeratorRef enumerator = fn FileManagerEnumeratorAtURL( dirURL, NULL, options, NULL, NULL )
CFURLRef url = fn EnumeratorNextObject( enumerator )
while ( url )
if ( fn StringIsEqual( fn URLPathExtension( url ), @"fb" ) )
NSLog(@"%@",url)
end if
url = fn EnumeratorNextObject( enumerator )
wend
end fn
 
fn EnumerateDirectoryAtURL( fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask ) )
 
HandleEvents
</syntaxhighlight>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=f48f8d5c2e2e85a8f80bcdc0124a35a5 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim sTemp As String
Line 959 ⟶ 1,031:
Next
 
End</langsyntaxhighlight>
Output:
<pre>
Line 973 ⟶ 1,045:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">Walk := function(name, op)
local dir, file, e;
dir := Directory(name);
Line 989 ⟶ 1,061:
 
# This will print filenames
Walk(".", Display);</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,021 ⟶ 1,093:
func main() {
filepath.Walk("/", VisitFile)
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Search text files in current directory tree in a depth-first fashion:
 
<langsyntaxhighlight lang="groovy">new File('.').eachFileRecurse {
if (it.name =~ /.*\.txt/) println it;
}</langsyntaxhighlight>
 
Shorter variant:
<langsyntaxhighlight lang="groovy">new File('.').eachFileRecurse ~/.*\.txt/, { println it }</langsyntaxhighlight>
 
Variant processing only files:
<langsyntaxhighlight lang="groovy">new File('.').eachFileRecurse FILES, ~/.*\.txt/, { println it }</langsyntaxhighlight>
 
Flexible search, traversal can be adapted by providing various options in the options Map, see documentation of method:
[http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/File.html#traverse(java.util.Map,%20groovy.lang.Closure) traverse(Map options, Closure closure)]
<langsyntaxhighlight lang="groovy">new File('.').traverse(
type : FILES,
nameFilter : ~/.*\.txt/,
preDir : { if (it.name == '.svn') return SKIP_SUBTREE },
) { println it }
</syntaxhighlight>
</lang>
 
=={{header|GUISS}}==
Here we list all files that match the pattern m*.txt in "My Documents" and all of its subfolders:
<langsyntaxhighlight lang="guiss">Start,Find,Files and Folders,Dropdown: Look in>My Documents,
Inputbox: filename>m*.txt,Button:Search</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 1,054 ⟶ 1,126:
Using the packages [http://hackage.haskell.org/package/directory-1.2.5.0/docs/System-Directory.html#v:getCurrentDirectory directory] and [https://hackage.haskell.org/package/filemanip-0.3.6.3/docs/System-FilePath-Find.html#v:find filemanip]
 
<langsyntaxhighlight lang="haskell">import System.Environment
import System.Directory
import System.FilePath.Find
Line 1,064 ⟶ 1,136:
dir <- getCurrentDirectory
files <- search pat dir
mapM_ putStrLn files</langsyntaxhighlight>
or more classic way:
<langsyntaxhighlight lang="haskell">import System.FilePath.Posix
import System.Directory
import System.IO
Line 1,086 ⟶ 1,158:
| takeExtension fname == ".hs" = putStrLn fname
| otherwise = return ()
dirWalk worker "."</langsyntaxhighlight>
 
== Icon and Unicon ==
Line 1,092 ⟶ 1,164:
Icon doesn't support 'stat' or 'open' of a directory; however, information can be obtained by use of the <code>system</code> function to access command line.
==={{header|Unicon}}===
<syntaxhighlight lang="unicon">
<lang Unicon>
###########################
# A sequential solution #
Line 1,165 ⟶ 1,237:
return D
}
end</langsyntaxhighlight>
 
=={{header|IDL}}==
<langsyntaxhighlight lang="idl">result = file_search( directory, '*.txt', count=cc )</langsyntaxhighlight>
This will descend down the directory/ies in the variable <tt>"directory"</tt> (which can be an array) returning an array of strings with the names of the files matching "*.txt" and placing the total number of matches into the variable <tt>"cc"</tt>
 
=={{header|J}}==
<langsyntaxhighlight lang="j">require 'dir'
>{."1 dirtree '*.html'</langsyntaxhighlight>
 
The verb <tt>dirtree</tt> returns a file listing of a directory tree as a boxed matrix with file names in the first column. The primitives <tt>>{."1</tt> will return the unboxed contents of the first column.
Line 1,182 ⟶ 1,254:
{{works with|Java|1.4+}}
Done using no pattern. But with end string comparison which gave better results.
<langsyntaxhighlight lang="java">import java.io.File;
 
public class MainEntry {
Line 1,210 ⟶ 1,282:
}
}
}</langsyntaxhighlight>
{{works with|Java|7+}}
Luckily, <code>java.nio.file.Files</code> gives us a <code>walkFileTree</code> method that does exactly what this task calls for.
<langsyntaxhighlight lang="java5">import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
Line 1,231 ⟶ 1,303:
});
}
}</langsyntaxhighlight>
{{works with|Java|8+}}
<langsyntaxhighlight lang="java">import java.io.IOException;
import java.nio.file.*;
 
Line 1,245 ⟶ 1,317:
}
}
</syntaxhighlight>
</lang>
 
=={{header|JavaScript}}==
{{works with|JScript}}
<langsyntaxhighlight lang="javascript">var fso = new ActiveXObject("Scripting.FileSystemObject");
 
function walkDirectoryTree(folder, folder_name, re_pattern) {
Line 1,278 ⟶ 1,350:
}
 
walkDirectoryTree(dir, dir.name, '\\.txt$');</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|1.2}}
 
<langsyntaxhighlight lang="julia">rootpath = "/home/user/music"
pattern = r".mp3$"
 
Line 1,290 ⟶ 1,362:
if occursin(pattern, file) println(file) end
end
end</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.2.0
 
import java.io.File
Line 1,307 ⟶ 1,379:
for (file in files) println(file)
}
</syntaxhighlight>
</lang>
 
Output (Ubuntu 14.04):
Line 1,320 ⟶ 1,392:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">// care only about visible files and filter out any directories
define dir -> eachVisibleFilePath() => {
return with name in self -> eachEntry where #name -> second != io_dir_dt_dir where not(#name -> first -> beginswith('.')) select .makeFullPath(#name -> first)
Line 1,349 ⟶ 1,421:
do #matchingfilenames -> insert(#filename)
 
#matchingfilenames</langsyntaxhighlight>
-> array(myfile.lasso, test.lasso, rosetta.lasso)
 
=={{header|LiveCode}}==
<syntaxhighlight lang="livecode">function pathsForDirectoryAndWildcardPattern pDirectory, pWildcardPattern
<lang LiveCode>function recurDir dir, ext
-- returns a return-delimited list of long file names
set the defaultFolder to dir
-- the last character in the list is a return, unless the list is empty
repeat for each line fi in the files
if fileExt(fi) = ext then
filter files(pDirectory) with pWildcardPattern
put the longfilepath of fi & cr after fileList
repeat for each line tFile endin ifit
put pDirectory & slash & tFile & cr after tPaths
end repeat
end repeat for each line di in the folders
if di is not "." and di is not ".." then
filter folders(pDirectory) without ".."
put recurDir((dir & slash & di), ext) & cr after fileList
repeat for each line tFolder endin ifit
put pathsForDirectoryAndWildcardPattern(pDirectory & slash & tFolder, pWildcardPattern) after tPaths
end repeat
end repeat
filter fileList without empty
return fileList
return tPaths
end recurDir
end pathsForDirectoryAndWildcardPattern</syntaxhighlight>
 
function fileExt f
set the itemdel to "."
return the last item of f
end fileExt</lang>
Example
<syntaxhighlight lang="livecode">put pathsForDirectoryAndWildcardPattern(the documents folder, "*.livecode*"</syntaxhighlight>
<lang LiveCode>put recurDir(the home folder & slash & "music", "mp3")</lang>
Output
<pre>...
<pre>... /Users/xxx/music/albumx/trackx.mp3
/Users/xxx/musicDocuments/albumx/trackx2abc.mp3livecode
/Users/xxx/musicDocuments/albumy/trackydef.mp3 ...</pre>livecodescript
...</pre>
<nowiki>--~~~~</nowiki>
 
=={{header|Lua}}==
Lua itself is extremely spartanic as it is meant for embedding. As lfs (LuaFileSystem) is about as standard an extension as it gets, we use that.
<langsyntaxhighlight Lualang="lua">local lfs = require("lfs")
 
-- This function takes two arguments:
Line 1,419 ⟶ 1,490:
for f in find("directory", function(self) return "directory" == lfs.attributes(self, "mode") end) do
print(f)
end</langsyntaxhighlight>
 
Lua 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.
<langsyntaxhighlight Lualang="lua">-- Gets the output of given program as string
-- Note that io.popen is not available on all platforms
local function getOutput(prog)
Line 1,452 ⟶ 1,523:
print(filename)
end
end</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
The built-in function <code>FileNames</code> does exactly this:
:<code>FileNames[]</code> lists all files in the current working directory.
Line 1,462 ⟶ 1,533:
:<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, find all files on the hard drive):
<langsyntaxhighlight Mathematicalang="mathematica">FileNames["*"]
FileNames["*.png", $RootDirectory]
FileNames["*", {"*"}, Infinity]</langsyntaxhighlight>
the result can be printed with Print /@ FileNames[....]
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">function walk_a_directory_recursively(d, pattern)
f = dir(fullfile(d,pattern));
for k = 1:length(f)
Line 1,481 ⟶ 1,552:
end;
end;
end; </langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">fn walkDir dir pattern =
(
dirArr = GetDirectories (dir + "\\*")
Line 1,501 ⟶ 1,572:
)
 
walkDir "C:" "*.txt"</langsyntaxhighlight>
 
=={{header|MoonScript}}==
MoonScript compiles to Lua, which itself is extremely spartanic as it is meant for embedding. As lfs (LuaFileSystem) is about as standard an extension as it gets, we use that.
 
<langsyntaxhighlight MoonScriptlang="moonscript">lfs = require "lfs"
 
-- This function takes two arguments:
Line 1,527 ⟶ 1,598:
 
-- List directories
print f for f in find "templates", => "directory" == lfs.attributes @, "mode"</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">import Nanoquery.IO
 
def get_files(dirname)
Line 1,555 ⟶ 1,626:
println file
end
end</langsyntaxhighlight>
 
=={{header|Nim}}==
The “os” standard module provides an iterator to walk recursively a directory. The iterator allows some filtering about the kind of entry to consider: real files (default), symbolic links to files, directories, symbolic links to directories. It doesn’t allow to specify a pattern, so filtering on name should be done using another mechanism (for instance, regular expressions).
 
<langsyntaxhighlight lang="nim">import os, re
 
for file in walkDirRec "/":
if file.match re".*\.mp3":
echo file</langsyntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">use System.IO.File;
 
class Test {
Line 1,594 ⟶ 1,665:
};
}
}</langsyntaxhighlight>
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">NSString *dir = NSHomeDirectory();
NSDirectoryEnumerator *de = [[NSFileManager defaultManager] enumeratorAtPath:dir];
 
for (NSString *file in de)
if ([[file pathExtension] isEqualToString:@"mp3"])
NSLog(@"%@", file);</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">#!/usr/bin/env ocaml
#load "unix.cma"
#load "str.cma"
Line 1,635 ⟶ 1,706:
let results = walk_directory_tree "/usr/local/lib/ocaml" ".*\\.cma" in
List.iter print_endline results;
;;</langsyntaxhighlight>
 
=={{header|ooRexx}}==
===version 1===
<langsyntaxhighlight lang="oorexx">/* REXX ---------------------------------------------------------------
* List all file names on my disk D: that contain the string TTTT
*--------------------------------------------------------------------*/
Line 1,648 ⟶ 1,719:
If pos('TTTT',translate(file.i))>0 Then
say file.i
end</langsyntaxhighlight>
{{out}}
<pre>1127869 files on disk
Line 1,656 ⟶ 1,727:
===version 2===
Get only files matching the file-spec.
<langsyntaxhighlight lang="oorexx">/* REXX ---------------------------------------------------------------
* List all file names on my disk D: that contain the string TTTT
*--------------------------------------------------------------------*/
Line 1,665 ⟶ 1,736:
If pos('TTTT',translate(file.i))>0 Then
say file.i
end </langsyntaxhighlight>
{{out}}
<pre>3 files found
Line 1,673 ⟶ 1,744:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
[Path] = {Module.link ['x-oz://system/os/Path.ozf']}
[Regex] = {Module.link ['x-oz://contrib/regex']}
Line 1,691 ⟶ 1,762:
end
in
{WalkDirTree "." ".*\\.oz$" System.showInfo}</langsyntaxhighlight>
 
=={{header|Perl}}==
Line 1,698 ⟶ 1,769:
 
{{works with|Perl|5.x}}
<langsyntaxhighlight lang="perl">use File::Find qw(find);
my $dir = '.';
my $pattern = 'foo';
my $callback = sub { print $File::Find::name, "\n" if /$pattern/ };
find $callback, $dir;</langsyntaxhighlight>
 
Or if you need maximum performance and are on a 'nix system, open a pipe to the GNU <tt>find</tt> program:
 
<langsyntaxhighlight lang="perl">sub shellquote { "'".(shift =~ s/'/'\\''/gr). "'" }
 
sub find_files {
Line 1,718 ⟶ 1,789:
}
 
find_files('.', '*.mp3');</langsyntaxhighlight>
 
Or using the recently popular Path::Tiny
 
<syntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Walk_a_directory/Recursively
use warnings;
use Path::Tiny;
 
path('.')->visit( sub {/\.c$/ and print "$_\n"}, {recurse => 1} );</syntaxhighlight>
 
=={{header|Phix}}==
Line 1,724 ⟶ 1,805:
There is a builtin routine for this, walk_dir() - if interested you can find the full implementation in builtins\file.e (an autoinclude).
 
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">find_pfile</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">pathname</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">dirent</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">match</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"pfile.e"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">dirent</span><span style="color: #0000FF;">[</span><span style="color: #000000;">D_NAME</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">then</span>
Line 1,734 ⟶ 1,815:
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">walk_dir</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"C:\\Program Files (x86)\\Phix"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">find_pfile</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
 
Passing 1 as the third parameter makes it scan recursively.
Line 1,746 ⟶ 1,827:
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php">function findFiles($dir = '.', $pattern = '/./'){
$prefix = $dir . '/';
$dir = dir($dir);
Line 1,758 ⟶ 1,839:
}
}
findFiles('./foo', '/\.bar$/');</langsyntaxhighlight>
This implementation uses Perl compatible regular expressions to match the whole path of the file
 
===PHP BFS (Breadth First Search)===
<syntaxhighlight lang="php">/*
<lang PHP>/*
This script performs a BFS search with recursion protection
it is often faster to search using this method across a
Line 1,850 ⟶ 1,931:
}
closedir($dh);
}</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(let Dir "."
(recur (Dir)
(for F (dir Dir)
Line 1,861 ⟶ 1,942:
(recurse Path) ) # Yes: Recurse
((match '`(chop "s@.l") (chop F)) # Matches 's*.l'?
(println Path) ) ) ) ) ) ) # Yes: Print it</langsyntaxhighlight>
{{out}}
<pre>"./src64/sym.l"
Line 1,869 ⟶ 1,950:
=={{header|Pop11}}==
Built-in procedure <code>sys_file_match</code> searches directories or directory trees using shell-like patterns (three dots indicate search for subdirectory tree).
<langsyntaxhighlight lang="pop11">lvars repp, fil;
;;; create path repeater
sys_file_match('.../*.p', '', false, 0) -> repp;
Line 1,876 ⟶ 1,957:
;;; print the path
printf(fil, '%s\n');
endwhile;</langsyntaxhighlight>
 
=={{header|PowerShell}}==
In PowerShell the <code>Get-ChildItem</code> cmdlet allows for recursive filtering on file names with simple wildcards:
<langsyntaxhighlight lang="powershell">Get-ChildItem -Recurse -Include *.mp3</langsyntaxhighlight>
For more complex filtering criteria the result of <code>Get-ChildItem</code> can be piped into the <code>Where-Object</code> cmdlet:
<langsyntaxhighlight lang="powershell">Get-ChildItem -Recurse |
Where-Object { $_.Name -match 'foo[0-9]' -and $_.Length -gt 5MB }</langsyntaxhighlight>
To perform an action on every matching file the results can be piped into the <code>ForEach-Object</code> cmdlet:
<langsyntaxhighlight lang="powershell">Get-ChildItem -Recurse |
Where-Object { $_.Name -match 'foo[0-9]' } |
ForEach-Object { ... }</langsyntaxhighlight>
''Note:'' To include only ''files'' instead of directories too each of the above needs an additional<code>Where-Object</code> filter:
<langsyntaxhighlight lang="powershell">| Where-Object { !$_.PSIsContainer }</langsyntaxhighlight>
 
 
=={{header|Prolog}}==
{{works with|Swi-Prolog|8.3}}
<syntaxhighlight lang="prolog">
<lang Prolog>
% submitted by Aykayayciti (Earl Lamont Montgomery)
% altered from fsaenzperez April 2019
Line 1,932 ⟶ 2,013:
;
format('Unknown: ~w~n',[File])
).</langsyntaxhighlight>
 
output :
<langsyntaxhighlight Prologlang="prolog">?- test_run.
File: GMFBridge.ax
File: libeay32.dll
Line 1,951 ⟶ 2,032:
File: MS-PL.txt
File: MSR-SSLA.txt
</syntaxhighlight>
</lang>
 
 
Line 1,958 ⟶ 2,039:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.s WalkRecursive(dir,path.s,Pattern.s="\.txt$")
Static RegularExpression
If Not RegularExpression
Line 1,980 ⟶ 2,061:
EndIf
Wend
EndProcedure</langsyntaxhighlight>
<langsyntaxhighlight PureBasiclang="purebasic">;- Implementation; Find all .log-files in the C:\Windows tree
ExamineDirectory(1,"C:\WINDOWS\","")
WalkRecursive(1,"C:\WINDOWS\","\.log$")
FinishDirectory(1)</langsyntaxhighlight>
 
 
Line 1,991 ⟶ 2,072:
=={{header|Prolog}}==
{{works with|Swi-Prolog|8.3}}
<syntaxhighlight lang="prolog">% submitted by Aykayayciti (Earl Lamont Montgomery)
<lapg Prolog>
% submitted by Aykayayciti (Earl Lamont Montgomery)
% altered from fsaenzperez April 2019
% (swi-prolog.discourse-group)
Line 2,030 ⟶ 2,110:
;
format('Unknown: ~w~n',[File])
).</langsyntaxhighlight>
 
output :
<langsyntaxhighlight Prologlang="prolog">?- test_run.
File: GMFBridge.ax
File: libeay32.dll
Line 2,048 ⟶ 2,128:
File: MS-PL-Eula.rtf
File: MS-PL.txt
File: MSR-SSLA.txt</syntaxhighlight>
</lang>
 
 
 
 
 
=={{header|Python}}==
{{works with|Python|3.x}}
Use the standard [https://docs.python.org/3/library/pathlib.html#pathlib.Path.rglob pathlib.Path.rglob()] module to recursively walk a directory with optional filter.
<langsyntaxhighlight lang="python">
from pathlib import Path
 
for path in Path('.').rglob('*.*'):
print(path)
</syntaxhighlight>
</lang>
 
{{works with|Python|3.x}}
{{works with|Python|2.3+}}
This uses the standard [http://docs.python.org/py3k/library/os.html?highlight=os.walk#os.walk os.walk()] module function to walk a directory tree, and the [http://docs.python.org/py3k/library/fnmatch.html fnmatch] module for matching file names.
<langsyntaxhighlight lang="python">import fnmatch
import os
 
Line 2,076 ⟶ 2,151:
for root, dirs, files in os.walk(rootPath):
for filename in fnmatch.filter(files, pattern):
print( os.path.join(root, filename))</langsyntaxhighlight>
{{works with|Python|<nowiki>2.x</nowiki>}}
{{works with|Python|<nowiki>3.x</nowiki>}}
A more strictly comparable port of this 2.3+ code to earlier versions of Python would be:
<langsyntaxhighlight lang="python">from fnmatch import fnmatch
import os, os.path
 
Line 2,088 ⟶ 2,163:
print os.path.join(dir, filename)
 
os.path.walk('/', print_fnmatches, '*.mp3')</langsyntaxhighlight>
The old ''os.path.walk'' function was a challenge for many to use because of the need to pass a function into the walk, and any arguments to that function through to it ... as shown. It's sometimes useful to pass mutable objects (lists, dictionaries, or instances of user-defined classes) to the inner function ... for example, to collect all the matching files for later processing.
 
Line 2,095 ⟶ 2,170:
{{libheader|Path}}
(''Note:'' This uses a non-standard replacement to the '''os.path''' module)
<langsyntaxhighlight lang="python">from path import path
 
rootPath = '/'
Line 2,102 ⟶ 2,177:
d = path(rootPath)
for f in d.walkfiles(pattern):
print f</langsyntaxhighlight>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">dir("/bar/foo", "mp3",recursive=T)</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
-> (for ([f (in-directory "/tmp")] #:when (regexp-match? "\\.rkt$" f))
(displayln f))
... *.rkt files including in nested directories ...
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,119 ⟶ 2,194:
 
Using the [https://github.com/tadzik/File-Find/ File::Find] module:
<syntaxhighlight lang="raku" perl6line>use File::Find;
 
.say for find dir => '.', name => /'.txt' $/;</langsyntaxhighlight>
 
Alternatively, a custom solution that provides the same interface as the built-in (non-recursive) <tt>dir</tt> function, and uses <tt>gather</tt>/<tt>take</tt> to return a lazy sequence:
 
<syntaxhighlight lang="raku" perl6line>sub find-files ($dir, Mu :$test) {
gather for dir $dir -> $path {
if $path.basename ~~ $test { take $path }
Line 2,132 ⟶ 2,207:
}
.put for find-files '.', test => /'.txt' $/;</langsyntaxhighlight>
 
Or if you value performance over portability, here's a function that runs the GNU <tt>find</tt> program and returns a lazy sequence of the files it finds. Parameters are not subjected to shell expansion, and the null-byte (which cannot be present in file paths) is used as the path delimiter, so it should be pretty safe.
 
<syntaxhighlight lang="raku" perl6line>sub find-files ($dir, :$pattern) {
run('find', $dir, '-iname', $pattern, '-print0', :out, :nl«\0»).out.lines;
}
 
.say for find-files '.', pattern => '*.txt';</langsyntaxhighlight>
 
=={{header|Rascal}}==
<langsyntaxhighlight lang="rascal">//usage example: To list just Rascal source files, Walk(|home:///workspace/|, ".rsc");
module Walk
import String;
Line 2,153 ⟶ 2,228:
elseif (isDirectory(a+entry))
Walk(a+entry, pattern);
}</langsyntaxhighlight>
 
=={{header|REALbasic}}==
<langsyntaxhighlight lang="vb">Sub printFiles(parentDir As FolderItem, pattern As String)
For i As Integer = 1 To parentDir.Count
If parentDir.Item(i).Directory Then
Line 2,168 ⟶ 2,243:
End If
Next
End Sub</langsyntaxhighlight>
Accepts a FolderItem object and a Regex pattern as a string:
<syntaxhighlight lang="vb">
<lang vb>
Dim f As FolderItem = GetFolderItem("C:\Windows\system32")
Dim pattern As String = "((?:[a-z][a-z]+))(\.)(dll)" //all file names ending in .dll
printFiles(f, pattern)</langsyntaxhighlight>
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">Red []
 
walk: func [
Line 2,201 ⟶ 2,276:
]
 
walk/where file %/home/user/ [print file] rules</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 2,207 ⟶ 2,282:
{{works with|Regina}}
The following program was tested in a DOS window under Windows/XP and should work for all Microsoft Windows.
<langsyntaxhighlight lang="rexx">/*REXX program shows all files in a directory tree that match a given search criteria.*/
parse arg xdir; if xdir='' then xdir='\' /*Any DIR specified? Then use default.*/
@.=0 /*default result in case ADDRESS fails.*/
Line 2,224 ⟶ 2,299:
do j=1 for #; say @.j /*show all the files that met criteria.*/
end /*j*/
exit @.0+rc /*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''output''' &nbsp; when the following was used: &nbsp; <tt> I:\firefox*.exe </tt>
<pre>
Line 2,239 ⟶ 2,314:
{{trans|BATCH-file}}
Works on Windows with ooRexx and Regina (not much REXX code in it)
<langsyntaxhighlight lang="rexx">'dir /s /b "%windir%\System32\*.exe"'</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see "Testing DIR() " + nl
mylist = dir("C:\Ring")
Line 2,253 ⟶ 2,328:
next
see "Files count : " + len(mylist)
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,283 ⟶ 2,358:
Using the Find core Module:
 
<langsyntaxhighlight lang="ruby">require 'find'
 
Find.find('/your/path') do |f|
# print file and path to screen if filename ends in ".mp3"
puts f if f.match(/\.mp3\Z/)
end</langsyntaxhighlight>
 
A little less verbose example using a shortcut for the glob method of Dir:
 
<langsyntaxhighlight lang="ruby">puts Dir['**/*.mp3']</langsyntaxhighlight>
 
=={{header|Rust}}==
Line 2,298 ⟶ 2,373:
Using std::fs::walk_dir (unstable as of Rust 1.1) with imperative for-loop:
 
<langsyntaxhighlight lang="rust">#![feature(fs_walk)]
 
use std::fs;
Line 2,310 ⟶ 2,385:
}
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
This is not implemented in the Scala library. Here is a simple solution, building on [[Java]] class ''<code>java.io.File</code>'':
 
<langsyntaxhighlight lang="scala">import java.io.File
 
object `package` {
Line 2,330 ⟶ 2,405:
for(f <- walkTree(dir)) println(f)
for(f <- walkTree(dir) if f.getName.endsWith(".mp3")) println(f)
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
Varies slightly depending on the implementation of scheme.
{{works with|Chicken Scheme}}
<langsyntaxhighlight lang="scheme">(use posix)
(use files)
(use srfi-13)
Line 2,350 ⟶ 2,425:
(FN MYPATH) )))) (directory PATH #t) ))
 
(walk (lambda (X) (cond ((string-suffix? ".scm" X) (display X)(newline) ))) "/home/user/")</langsyntaxhighlight>
See also: '''(find-files ...)''' function in the '''posix''' module.
{{works with|Gauche}}
<langsyntaxhighlight lang="scheme">(use file.util)
(use srfi-13)
 
Line 2,366 ⟶ 2,441:
(FN MYPATH) )))) (directory-list PATH :add-path? #t :children? #t ) ))
 
(walk (lambda (X) (cond ((string-suffix? ".scm" X) (display X)(newline) ))) "/home/user/")</langsyntaxhighlight>
See also: '''(find-file-in-paths ...)''' function in the '''file.util''' module.
{{works with|PLT Scheme}}
<langsyntaxhighlight lang="scheme">#lang scheme
 
(require srfi/13)
Line 2,384 ⟶ 2,459:
(FN MYPATH) )))) (directory-list PATH)))
 
(walk (lambda (X) (cond ((string-suffix? ".scm" (path->string X)) (display X)(newline) ))) "/home/user/")</langsyntaxhighlight>
See also: '''(find-files ...)''' function in the '''file''' module.
{{out|Sample output}}
Line 2,402 ⟶ 2,477:
[http://seed7.sourceforge.net/libraries/osfiles.htm#fileType%28in_string%29 fileType].
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "osfiles.s7i";
 
Line 2,424 ⟶ 2,499:
begin
walkDir(".", ".sd7");
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func traverse(Block callback, Dir dir) {
dir.open(\var dir_h) || return nil
 
Line 2,448 ⟶ 2,523:
}
} => dir
)</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<langsyntaxhighlight lang="smalltalk">Directory extend [
wholeContent: aPattern do: twoBlock [
self wholeContent: aPattern withLevel: 0 do: twoBlock.
Line 2,477 ⟶ 2,552:
]
]
].</langsyntaxhighlight>
 
<langsyntaxhighlight lang="smalltalk">|d|
d := Directory name: '.'.
d wholeContent: '\.st$' do: [ :f :l |
0 to: l do: [ :i | (Character tab) display ].
f displayNl
].</langsyntaxhighlight>
 
=={{header|Swift}}==
{{works with|Swift|3.0}}
<langsyntaxhighlight lang="swift">import Foundation
 
let fileSystem = FileManager.default
Line 2,508 ⟶ 2,583:
}
}
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{works with|Tcl|8.5}}
<langsyntaxhighlight lang="tcl">
package require fileutil
proc walkin {path cmd} {
Line 2,544 ⟶ 2,619:
}
}}}
</syntaxhighlight>
</lang>
 
=={{header|TXR}}==
There is more than one way to do this in TXR. A recursive walk could be coded using <code>open-directory</code> and <code>getline</code>. Or FFI could be used to gain access to some platform-specific functions like Microsoft's <code>FindFirstFile</code> and so forth.
 
===Using <code>ftw</code>===
TXR wraps and exposes the POSIX <code>nftw</code> function, which is demonstrated here. This function encapsulates a tree walk, and uses callbacks to inform the program of visited filesystem tree nodes, and of error situations. We can use a <code>lambda</code> for the code walk, or wrap the invocation of <code>ftw</code> with a macro which hides the <code>lambda</code> syntax.
 
Line 2,554 ⟶ 2,630:
Here we use the <code>build</code> macro for procedural list building to gather all of the found paths into a list, which is implicitly returned. The callback is an explicit <code>lambda</code>:
 
<langsyntaxhighlight lang="txrlisp">(build (ftw "." (lambda (path type stat level base)
(if (ends-with ".tl" path)
(add path)))))</langsyntaxhighlight>
 
{{out}}
 
<langsyntaxhighlight lang="txrlisp">("./tests/016/arith.tl" "./tests/014/dgram-stream.tl" "./tests/014/socket-basic.tl"
"./tests/sock-common.tl" "./tests/012/ifa.tl" "./tests/012/except.tl"
"./tests/012/fini.tl" "./tests/012/oop.tl" "./tests/012/circ.tl"
Line 2,577 ⟶ 2,653:
"./share/txr/stdlib/struct.tl" "./share/txr/stdlib/getput.tl"
"./share/txr/stdlib/path-test.tl" "./share/txr/stdlib/with-resources.tl"
"./share/txr/stdlib/yield.tl" "./share/txr/stdlib/conv.tl" "./share/txr/stdlib/termios.tl")</langsyntaxhighlight>
 
For a regex pattern we can replace <code>(endswith ".tl" path)</code> with something like <code>(m$ path #/\.tl/)</code>.
Line 2,591 ⟶ 2,667:
 
A nice approach would be to capture a continuation in the callback, and then obtain the walk elements lazily; alas, capturing a continuation from a C library function's callback is not permitted, because the capture would span foreign stack frames.
 
===Using <code>glob*</code>===
 
TXR has a <code>glob*</code> function which, like <code>glob</code> is built on the POSIX C library function. <code>glob*</code> also provides Bash-style brace expansion, as well as the double star pattern, which we can use to find files recursively:
 
<syntaxhighlight lang="txrlisp">(glob* "**/*.c")</syntaxhighlight>
 
{{out}}
 
<syntaxhighlight lang="txrlisp">("args.c" "arith.c" "autoload.c" "buf.c" "cadr.c" "chksum.c" "chksums/crc32.c"
"chksums/md5.c" "chksums/sha1.c" "chksums/sha256.c" "combi.c"
"debug.c" "eval.c" "ffi.c" "filter.c" "ftw.c" "gc.c" "glob.c"
"gzio.c" "hash.c" "itypes.c" "lib.c" "linenoise/example.c" "linenoise/linenoise.c"
"match.c" "mpi/mpi.c" "mpi/mplogic.c" "parser.c" "protsym.c"
"psquare.c" "rand.c" "regex.c" "signal.c" "socket.c" "stream.c"
"struct.c" "strudel.c" "sysif.c" "syslog.c" "termios.c" "time.c"
"tree.c" "txr.c" "unwind.c" "utf8.c" "vm.c")</syntaxhighlight>
 
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
The "find" command gives a one-line solution for simple patterns:
<langsyntaxhighlight lang="bash">find . -name '*.txt' -type f </langsyntaxhighlight>
"find" can also be used to find files matching more complex patterns as illustrated in the section on [[#UnixPipes|Unix Pipes]] below.
 
Using "bash" version 4 or later, you can use "globstar" or "dotglob", depending on whether you want hidden directories to be searched:
<langsyntaxhighlight lang="bash">#! /bin/bash
# Warning: globstar excludes hidden directories.
# Turn on recursive globbing (in this script) or exit if the option is not supported:
Line 2,609 ⟶ 2,702:
echo "$f"
fi
done</langsyntaxhighlight>
Here is a solution that does not use "find".
<langsyntaxhighlight lang="bash">#! /bin/bash
 
indent_print()
Line 2,653 ⟶ 2,746:
}
 
walk_tree "$1" "\.sh$"</langsyntaxhighlight>
A simplified version that gives the same output:
<langsyntaxhighlight lang="bash">#! /usr/bin/env bash
walk_tree() {
Line 2,668 ⟶ 2,761:
}
walk_tree "$1" "\.sh$"</langsyntaxhighlight>
 
=={{header|UnixPipes}}==
As illustrated [[#UNIX Shell|above]], the "find" command can be used with the -name option to match simple patterns. To find files matching more complex patterns, the results of "find" can be piped, e.g.
<langsyntaxhighlight lang="bash">find . -type f | egrep '\.txt$|\.TXT$'</langsyntaxhighlight>
One way to run a command against each file that is found is to use "xargs", but if there is any possibility that a filename contains a space or tab character, then the following model should be used:
<langsyntaxhighlight lang="bash"> find . -type f -name "*.txt" -print0 | xargs -0 fgrep sometext</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|9.0+}}
This uses the OS pattern matching
<langsyntaxhighlight lang="vbnet">Sub walkTree(ByVal directory As IO.DirectoryInfo, ByVal pattern As String)
For Each file In directory.GetFiles(pattern)
Console.WriteLine(file.FullName)
Line 2,686 ⟶ 2,779:
walkTree(subDir, pattern)
Next
End Sub</langsyntaxhighlight>
 
=={{header|Wren}}==
{{libheader|Wren-pattern}}
{{libheader|Wren-sort}}
<syntaxhighlight lang="wren">import "io" for Directory, File
import "./pattern" for Pattern
import "./sort" for Sort
 
var walk // recursive function
walk = Fn.new { |dir, pattern, found|
if (!Directory.exists(dir)) Fiber.abort("Directory %(dir) does not exist.")
var files = Directory.list(dir)
for (f in files) {
var path = dir + "/%(f)"
if (File.exists(path)) { // it's a file not a directory
if (pattern.isMatch(f)) found.add(f)
} else {
walk.call(path, pattern, found)
}
}
}
 
// get all C header files beginning with 'va' or 'vf'
var p = Pattern.new("v[a|f]+0^..h", Pattern.whole)
var found = []
walk.call("/usr/include", p, found)
Sort.quick(found)
for (f in found) System.print(f)</syntaxhighlight>
 
{{out}}
<pre>
valarray_after.h
valarray_array.h
valarray_before.h
valgrind.h
validate.h
values.h
vfio.h
vfio_ccw.h
vfs.h
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">d:=File.globular("..","s*.zkl")</langsyntaxhighlight>
Lots of options, here I'm using the defaults: recurse, just file matches (not directory names) and return a bit bucket of ASCIIZ strings.
{{out}}
Line 2,705 ⟶ 2,839:
</pre>
globular will write to a object that has a write method or just call a method or function, which is nice for sending data to other threads (eg multi-threaded find/grep). To do the above example in one shot (without saving the results):
<langsyntaxhighlight lang="zkl">File.globular("..","s*.zkl",True,0,Console.println)</langsyntaxhighlight>
 
=={{header|Zsh}}==
Zsh has recursive globbing. The GLOB_DOTS option allows files beginning with a period to be matched.
<langsyntaxhighlight lang="zsh">setopt GLOB_DOTS
print -l -- **/*.txt</langsyntaxhighlight>
GLOB_DOTS can be set temporarily with the 'D' modifier.
<langsyntaxhighlight lang="zsh">print -l -- **/*.txt(D)</langsyntaxhighlight>
 
{{omit from|ACL2|Very limited filesystem support.}}
9,476

edits