Skip to content

Instantly share code, notes, and snippets.

@ploubser
Last active April 21, 2020 15:13
Show Gist options
  • Save ploubser/da819276ade1b16b315b4fec78030b8a to your computer and use it in GitHub Desktop.
Save ploubser/da819276ade1b16b315b4fec78030b8a to your computer and use it in GitHub Desktop.
recursive_rename from moodle
#!/usr/bin/env ruby
#coding:utf-8
# This script is used to rename files to the name of their parent directory when downloaded from moodle.
# Given
#├── user1
#│   └── foo.pdf
#└── user2
# └── foo.pdf
#
# The expected result of ruby recursive_rename.rb target_dir/ pdf is
# user1.pdf
# user2.pdf
#
# Arguments
# ARGV[0] The target directory
# ARGV[1] The file extension to use
require 'fileutils'
target = ARGV[0]
extension = ARGV[1]
if target == nil || extension == nil
raise "Error. Script requires 2 arguments. Call like 'ruby recursive_rename.rb target_dir/ pdf"
end
Dir.children(target).each do |child|
child_dir = File.join(File.dirname(__FILE__), target, child)
if File.directory?(child_dir)
files = Dir.children(child_dir)
if files.size > 1
raise "Error. Found too many files in directory #{child_dir}"
end
filepath = File.join(child_dir,files[0])
FileUtils.cp(filepath, "#{child}.#{extension}")
else
raise "Error. Found something in the target dir that's not a directory - #{child_dir}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment