Batch rename components based on spreadsheet

I want what this thread is trying to achieve;

BUT, I have a spreadsheet of the component names that I want to rename and the names that I want them to be renamed after, I’m a beginner at Ruby, I want to learn how to do this as I go, but for now I want a quick and easy fix for this. I know Python and am not that much of a stranger at programming.

Thank you so much!

Ruby can read a text file -
so if you save the spread sheet as a CSV there are then methods to read it line by line.
Then split each line at the comma, read in the array’s elements into ‘old_name’ and ‘new_name’ and save those pairs into an array, and process the model’s definitions to rename one.
Wrap in in an operation so it’s undo-able…

model=Sketchup.active_model
model.start_operation('Compo Rename', true)
textlines=IO.read('path_to_csv_as_string') # get array of lines in CSV file
textlines.each{|pair|
  next unless pair =~ /[,]/ # we need a 'pair'
  pair.chomp! # we remove \n at end of string
  names=pair.split(',') # we get [old, new] array
  names.each{|name|
    old_name=name[0]
    new_name=name[1]
    defn=model.definitions[old_name] # returns nil if not there
    if defn
      defn.name=new_name
      puts "Definition #{old_name} renamed #{new_name}"
    else
      puts "Definition #{old_name} NOT found in the current model.definitions"
    end
  }
}
model.commit_operation

Run with the Ruby Console open so that you ca see the ‘puts’…
You really need to understand Ruby and the API, and look at similar RB files to understand how it all works…
https://ruby.sketchup.com/

1 Like

Had been playing with it for a few hours, have made scripts to handle this, even generated the csv entries into a string of declared arrays to copy and paste into the ruby console for processing, made a few breakthroughs, but am now having problems, it does not account for nested components, only the top level is accounted for.

Testing your script, it returns an error;

Error:
#<NoMethodError: undefined method `each’ for #String:0x000001eafbdc8178>

:3:in `' SketchUp:in `eval'

=> nil

can an IO.read have an each as a method? It might be the one that returns an error?

I haven’t tried the script, so thanks for the info…
Here v2 - I tested it this time and it works…

model=Sketchup.active_model
model.start_operation('Compo Rename', true)
textlines=IO.read('path_to_file.csv') # get array of lines in CSV file
textlines.split("\n").each{|pair| # pairs are \n separated
  next unless pair =~ /[,]/ # we need a 'pair' with a comma
  names=pair.split(',') # CSV separator
  old_name=names[0]
  new_name=names[1]
  defn=model.definitions[old_name] # returns nil if not there
  if defn
    defn.name=new_name
    puts "Definition #{old_name} renamed #{new_name}"
  else
    puts "Definition #{old_name} NOT found in the current model.definitions"
  end
}
model.commit_operation
1 Like

This worked marvelously. Thank you so much!