Ruby – Script que move arquivos com determinado padrão e conteudo

25 04 2016

Problema

Preciso mover aquivos que tenham determinado padrão e conteúdo de maneira rápida

Solução

Utilizei o Ruby com a opção de fork:

##################################################################################################################
# FUNCTIONS
##################################################################################################################
def read_file_with_encoding_safe  file_name
	file = File.new(file_name)
	text = file.read	
	if ! text.valid_encoding?
	  text = text.encode("UTF-16be", :invalid=>:replace, :replace=>"?").encode('UTF-8')
	end		
end

def process_files files, pattern, dir_out, group
	files.each do |file_name|
		text = read_file_with_encoding_safe file_name
		if text =~ /#{pattern}/ then			 
			puts file_name
			now = Time.now.strftime "%Y-%m-%d-%H-%M-%S-%z"
			target_path = "#{dir_out}/#{group}-#{now}.xml"
			File.rename file_name, target_path
		end
	end
end


##################################################################################################################
# MAIN
##################################################################################################################
# Find specific files on folders
# Verify if the file have some pattern and move the file to a output folder if pass
# Execute with fork process 
# Autor: Leonardo Cardoso Dias
# Date: 25/04/2016
##################################################################################################################
puts "Initing..."
folder="marco2016/03"
dir_out="processados"
pattern="nfeProc"
Dir.mkdir dir_out unless Dir.exist?(dir_out)

# Forking the process on folder 01
Process.fork do
	process_files Dir.glob("#{folder}/01/**/*.webedi"), pattern, dir_out, "A"
end

# Forking the process on folder 02
Process.fork do
	process_files Dir.glob("#{folder}/02/**/*.webedi"), pattern, dir_out, "B"
end

# Wait for all process finish
Process.waitall
puts "finished ...uhulll..see the output folder: #{folder}"
Anúncios

Ações

Information

Deixe um comentário

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair / Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair / Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair / Alterar )

Foto do Google+

Você está comentando utilizando sua conta Google+. Sair / Alterar )

Conectando a %s




%d blogueiros gostam disto: