簡體   English   中英

示例Bash腳本或命令以檢索目錄中的數字文件

[英]sample Bash script or command to retrieve number files in directory

我目錄中的文件數有問題

我用

$(ls /test -l | grep '^-' | wc -l)

但是通過這種方式,我只檢索同一路徑中的文件數量,但是如果我有子目錄,則不會檢索子目錄中的文件數量

  /test/1
  /test/1/2
  /test/1/3
  /test/1/4/1
  /test/1/4/2
  /test/1/5

我的問題是如何在/ test中檢索文件數量? 謝謝你的建議。

嘗試這個

targetDir=/test
find ${targetDir} -type f | wc -l

我希望這有幫助。

$(ls -lR /test | grep '^-' | wc -l)

更好地使用查找

$(find /test -type f | wc -l)

標准方法是使用find

find /test -type f | wc -l

其他方法包括使用外殼(例如bash 4)

shopt -s globstar
shopt -s dotglob
declare -i count=0
for file in **
do
  if [ -f "$file" ];then
     ((count++))
  fi
done
echo "total files: $count"

或一種編程語言,例如Perl / Python或Ruby

ruby -e 'a=Dir["**/*"].select{|x|File.file?(x)};puts a.size'

使用wc -l是最簡單的方法,但是如果您想准確地計數文件,則更為復雜:

count_files()
{
    local file_count=0
    while IFS= read -r -d '' -u 9
    do
        let file_count=$file_count+1
    done 9< <( find "$@" -type f -print0 )
    printf %d $file_count
}

另外,您可以使用它來同時計入多個目錄。

要測試它:

test_dir="$(mktemp -d)"
touch "${test_dir}/abc"
touch "${test_dir}/foo
bar
baz"
count_files "$test_dir"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM