user3278117
user3278117

Reputation: 95

Renaming every file in a directory, based off first line

Starting out in Ruby and trying to create a simple renaming Ruby script. Say I have a directory filled with resumes with randomized filenames like: Resume0001, Resume0012, Resume9123, Res_430. In general it doesn't matter what the starting name is.

I want my script to take in every file and rename (or create a new file) with the name of the file as the name of the resume owner. I understand that it depends on the resume layout of course, but, I am assuming that the first line will hold only the name of that person.

Given what I know, I am able to rename them by feeding in the arguments (files) manually. This would be fine if I only had like 5 resumes to do. My problem comes up when I try to feed my script a directory of about 10,000 resumes.

This is what I have so far:

puts "Renaming files..."

Dir.glob("Resumes") do |f|
    File.rename(f, f.readline())
end

puts "Renaming complete."

I have a couple ideas why this doesn't work/things I'm not sure about:

  1. f is just a String, not a file object which is why readline() doesn't work on it. (edit: f == filename, not a reference to the actual file object)

  2. I'm also getting a private method error. This also happens if I try something like

    first_line = f.readline() File.rename(f, first_line)

    I'm just having difficulties understanding what exactly the private method error is.

  3. I'm not entirely sure how specifying directory paths work. So let's say my .rb file is located documents\name\resume_converter\converter.rb. If my directory of resumes is also in the resume_converter folder (resume_converter\Resumes), I would specify it in Dir.glob("Resumes")? What if it was another file deeper? resume_converter\Dummy_folder\Resumes => Dir.glob("Dummy_folder\Resumes")?

  4. Is there framework support for what I'm trying to do? I have no practical Rails/framework knowledge but I imagine that a task like this has been done before using a framework?

So yeah, I'm stuck.

Upvotes: 1

Views: 385

Answers (1)

Eugene
Eugene

Reputation: 4879

Something like this should work:

require 'fileutils'

Dir.glob("Resumes/*").each do |f|
  name = File.open(f).readlines.first.strip # Strip off any whitespace or trailing newlines
  FileUtils.mv(f, "Resumes/#{name}")
end

Upvotes: 1

Related Questions