Recursively find only files under certain directory

Contents

Output

File list like this

example_dir1/1.txt
example_dir1/example_dir2/4.txt
example_dir1/example_dir2/3.txt
example_dir1/example_dir2/2.txt

Prerequisites

Prepare files like this

example_dir1/1.txt
example_dir1/example_dir2/4.txt
example_dir1/example_dir2/3.txt
example_dir1/example_dir2/2.txt

And pass directory name “example1” as parameter for the script


Code examples


JavaScript

var recursive = require("recursive-readdir");
let dir = ".";
if(typeof(process.argv[2]) !== "undefined"){
  dir = process.argv[2];
}
else{
  dir = ".";
}
recursive(dir, function (err, files) {
  for(const i in files) {
    console.log(files[i]);
  }
});

PHP

<?php
if(isset($argv[1])) {
  $dir = $argv[1];
}
else {
  $dir = '.';
}
$it = new RecursiveDirectoryIterator($dir);
foreach(new RecursiveIteratorIterator($it) as $file) {
  if(!is_dir($file)) {
    print $file."\n";
  }
}

Perl

use File::Find;
my $dir = $ARGV[0] || '/.';
my $wanted = sub {
  if(-f $_) {
    print $File::Find::name."\n";
  }
};
&find($wanted, $dir, );

Python

import sys
from os import walk
import os
import re

path = ""

try:
  sys.argv[1]
except:
  path = "."
else:
  path = sys.argv[1]

def find_files(dir):
  for root, dirs, files in walk(path):
    for file in files:
      if os.path.isdir(file):
        find_files(file)
      else:
        print(root, end = '')
        if not re.search(r"/$", root):
          print("/", end = "")
        else:
          pass
        print(file)
find_files(path)

Ruby

require 'find'
dir = ""
if ARGV[0]
  dir = ARGV[0]
else
  dir = "."
end

Find.find(dir) do |file|
  if File.file?(file)
    puts(file)
  end
end