[英]Search for a string in files in subdirectories
我需要找到包含<some_word>
所有字符串。 有MAIN目錄,我們必須搜索,可以有文件和其他目錄(帶文件)。 它必須進入一個目錄 - 檢查那里的所有文件<some_word>
,返回主目錄 - 輸入另一個directroy - 檢查那里的所有文件,返回主目錄......依此類推。 我沒有問題,當主目錄中只有文件...但不知道如何使用目錄...請幫助我。
要處理目錄中的所有文件:
Dir['**/*'].each do |filepath|
# filepath is a string path to the file or directory
# relative from the working directory of the script
end
因此,如果您已經有find_text_in_file( some_word, filepath )
,則可以執行以下操作:
Dir['**/*'].select{|f| File.file?(f) }.each do |filepath|
find_text_in_file( some_word, filepath )
end
請注意,上面將以深度優先遍歷搜索文件。 如果您想以廣度優先的方式進行搜索,可以改為使用:
files = Dir['**/*'].select{ |f| File.file?(f) }
files.sort_by{ |f| f.split(File::SEPARATOR).length }.each do |filepath|
find_text_in_file( some_word, filepath )
end
或者,如果您已經有find_word_in_directory( some_word, dirpath )
那么您可以執行以下操作:
Dir['**/*'].select{ |f| File.directory?(f) }.each do |dirpath|
find_word_in_directory( some_word, dirpath )
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.