2016-09-13 5 views
-1

ディレクトリ内のすべてのファイルを取得したいが、そのディレクトリ内のサブディレクトリには入れない。これまで私は使用しています。ループ内ディレクトリ内のファイルを取得しますが、サブディレクトリはありません

file=(path/to/my/files/*) 

for f in ${files[@]}; do ... 
+1

'find'を試しましたか? – Inian

+1

多分、ある日、 'bash'は' zsh'形式のグロブ修飾子を得るでしょう: 'files =(path/to/my/files/*(。))'。 – chepner

答えて

1

適切なエラーフリーの道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フラグは、特殊文字でファイルを処理します。

2

スキップサブディレクトリ:

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 
0

あなただけのファイルを取得したい場合は、それはそれと同じくらい簡単です:)

を尋ねる前に、宿題をしなさい:あなたはディレクトリの下のディレクトリを取得したい場合は

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 
+0

...どのように私はループすることができる変数にfindの結果を得るのですか? – myol

+0

簡単に: '#!/ bin/bash my_files =' find。 -maxdepth 1 -type f' $ my_filesのファイルです。 do echo $ file done – sestus

+0

私はあなたの納得のゆえに元の回答への応答を追加しました – sestus

関連する問題