ディレクトリ内のすべてのファイルを取得したいが、そのディレクトリ内のサブディレクトリには入れない。これまで私は使用しています。ループ内ディレクトリ内のファイルを取得しますが、サブディレクトリはありません
file=(path/to/my/files/*)
for f in ${files[@]}; do ...
ディレクトリ内のすべてのファイルを取得したいが、そのディレクトリ内のサブディレクトリには入れない。これまで私は使用しています。ループ内ディレクトリ内のファイルを取得しますが、サブディレクトリはありません
file=(path/to/my/files/*)
for f in ${files[@]}; do ...
適切なエラーフリーの道GNU
を使用すると、次のようなものが見つかります。
#!/bin/bash
while IFS= read -r -d '' file; do
# Your script/command(s) goes here
done < <(find . -maxdepth 1 -mindepth 1 -type f -print0)
man find
は-mindepth
と-maxdepth
フィールド
-maxdepth levels
Descend at most levels (a non-negative integer) levels of directories below the command line arguments. -maxdepth 0
means only apply the tests and actions to the command line arguments.
-mindepth levels
Do not apply any tests or actions at levels less than levels (a non-negative integer). -mindepth 1 means process all files except the command line arguments.
については、次ので、理想的-mindepth 1
と-maxdepth 1
はすなわち、現在のディレクトリ内の制限、複数のレベルでのファイルの検索を超えて行かないだろうと言います。そして、-print0
フラグは、特殊文字でファイルを処理します。
スキップサブディレクトリ:
for file in path/to/my/files/*; do
[[ -d $file ]] && continue
# do other stuff here
done
それは驚くほど効率的ではないのですが、あなたは、このようなファイルの配列を構築することができます:やっての
files=()
for file in path/to/my/files/*; do
[[ -d $file ]] || files+=("$file")
done
あなただけのファイルを取得したい場合は、それはそれと同じくらい簡単です:)
を尋ねる前に、宿題をしなさい:あなたはディレクトリの下のディレクトリを取得したい場合は
find <directory_name> -maxdepth 1 -type f
(ちょうど1レベル:
find <directory_name> -maxdepth 1 -type d
あなたは感謝のため@chepnerする(bashスクリプトでポイント
を取得彼のメモ):
#!/bin/bash
find . -maxdepth 1 -type f -print0 | while IFS= read -r -d '' file; do
echo "$file"
done
'find'を試しましたか? – Inian
多分、ある日、 'bash'は' zsh'形式のグロブ修飾子を得るでしょう: 'files =(path/to/my/files/*(。))'。 – chepner