1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Tclで指定ディレクトリ配下のファイルを再帰を使わずリストアップ

Posted at

指定ディレクトリ配下にあるファイルを再帰を使わずにリストアップする関数です。

proc find {{pattern "*"} {dir ""}} {
	set depth -1
	set retry -1
	while {$retry} {
		set wildcards [lrepeat [incr depth] *]
		lappend found {*}[glob -nocomplain -directory $dir -type f -join {*}$wildcards $pattern]
		set retry [llength [glob -nocomplain -directory $dir -type d -join {*}$wildcards *]]
	}
	return $found
}

dirを省略するとカレントディレクトリを起点に検索を始めます。

patternを省略すると全てのファイルをリストアップします。

patternには*.tclのようなglobパターンを指定できます。Windowsで試したら大文字と小文字は区別されませんでした。Linuxでは試していませんが、たぶん大文字と小文字は区別されると思います。

再帰を使わず実現できているカラクリはglobコマンドの-joinオプションです。globコマンドのヘルプには

-join
The remaining pattern arguments, after option processing, are treated as a single pattern obtained by joining the arguments with directory separators.

と書かれています。

どういう事かというと、-join * * * *.tclと書くと*/*/*.tclというパターンでファイルを検索するという意味になり、同じ深さの異なるディレクトリそれぞれでファイル検索を行うことになります。

この機能を利用して、

  1. -type fオプションでファイルをリストアップ
  2. -type dオプションでディレクトリが見つかったら-joinに与える*を増やして1に戻り、ディレクトリが無かったら終了

というループを回しているだけです。

Tclって、ちょくちょくこういう強引・・・もとい、強力な機能が地雷のようにシレッと用意してあったりして、そういうところも魅力のひとつだと思います。

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?