簡體   English   中英

一次統計目錄中的文件

[英]Count files in directory on a time

我正在使用macOSx,我想計算目錄中的所有文件,然后打印按上次修改時間排序的結果。 像這樣:

1241 2014-12-08 07:00:00 +0700
4123 2014-12-08 08:00:00 +0700
2241 2014-12-08 09:00:00 +0700

等等。我試過紅寶石,但我只能用這個來計算文件數:

dir = 'original'
puts Dir[File.join(dir, '**', '*')].count { |file| File.file?(file) }

或放入所有文件並按時間將其排序,如下所示:

Dir[File.join(dir, '**', '*')].sort_by{ |f| File.mtime(f) }

那我該怎么辦呢? 可能是bash腳本或ruby ...

不知道我是否理解請求。 您是否有子目錄或需要對子目錄中的所有文件進行排序? 如果沒有,我使用此命令

ls -lctr

說明

 -l      (The lowercase letter ``ell''.)  List in long format.  (See below.)  If the output is to a terminal, a total sum
         for all the file sizes is output on a line before the long listing.
 -c      Use time when file status was last changed for sorting (-t) or long printing (-l).
 -t      Sort by time modified (most recently modified first) before sorting the operands by lexicographical order.
 -r      Reverse the order of the sort to get reverse lexicographical order or the oldest entries first (or largest files
         last, if combined with sort by size

如果需要計數文件,請使用以下命令:

find . -type f |wc -l
arr = []
count = 0
Dir.glob("/path/**/*").each { |file| 
  if  File.file?(file)
    count+=1
    arr << File.mtime(file)
  end
}
puts count.to_s + " " + arr.sort.last.to_s
#=> 2241 2014-12-08 09:00:00 +0700

雖然這不會考慮子目錄文件

如果我理解正確

Dir["Other/**"].sort_by{ |f| File.mtime(f) }.each do |item|
  if File.directory? item  
    print "#{Dir[File.join(item, '**', '*')].count} #{File.mtime(item)}\n"
  end
end

您可以使用tap來計數文件,如下所示:

require 'fileutils'
dir = '.'
p Dir[File.join(dir, '**', '*')]
    .tap{|el| p el.length }
    .sort_by{ |f| File.mtime(f) }

哪個打印計數和文件排序數組。

這是bash腳本,可進入文件夾並從那里執行命令。

#!/bin/bash
curdir=$(pwd)
for f in $curdir/<parent folder name>/*
  do
     [ -d $f ] && cd "$f" && echo Entering into $f && wc -l
  done;

這是我的紅寶石代碼:

require "Date"
dir = 'original'

for date in 1..7 do
  for hour in 0..23 do
    d = DateTime.new(2014, 1, 1, hour, 0, 0)
    d1 = DateTime.new(2014, 1, 1, hour+1, 0, 0)
    time = d.strftime("%H:%M")
    time1 = d1.strftime("%H:%M")

    puts ("Files on time 12/0#{date}/2014 #{time} (from #{time} -- #{time1}) :")
    puts Dir[File.join(dir, '**', '*')].count {|file|
      if ("12/0#{date}/2014 #{time}" < File.mtime(file).strftime('%m/%d/%Y %I:%M')) && (File.mtime(file).strftime('%m/%d/%Y %I:%M') < "12/0#{date}/2014 #{time1}")
        File.file?(file)
      end
    }
  end
  puts ("Files on time 12/0#{date}/2014 23:00 (from 23:00 -- 00:00 next day) :")
  puts Dir[File.join(dir, '**', '*')].count {|file|
    if ("12/0#{date}/2014 23:00" < File.mtime(file).strftime('%m/%d/%Y %I:%M')) && (File.mtime(file).strftime('%m/%d/%Y %I:%M') < "12/0#{date+1}/2014 #{time1}")
      File.file?(file)
    end
  }
end

暫無
暫無

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

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