Skip to content

Instantly share code, notes, and snippets.

@12joan
Created June 30, 2024 21:10
Show Gist options
  • Save 12joan/a9b92a45b0be219acf6d7d737888872b to your computer and use it in GitHub Desktop.
Save 12joan/a9b92a45b0be219acf6d7d737888872b to your computer and use it in GitHub Desktop.
A Ruby script that uses the `file` command to add or change file extensions for a list of files
#!/usr/bin/ruby
require 'fileutils'
Entry = Struct.new(:path, :extension) do
def self.parse line
columns = line.chomp.split(/:\s*/)
return nil unless columns.length == 2
path, extensions = columns
return nil if extensions == '???'
extension = extensions.split('/').first
new(path, extension)
end
def path_without_extension
path.split('.').first
end
def move
new_path = path_without_extension + '.' + extension
FileUtils.mv(path, new_path) unless path == new_path
end
end
entries = `file --extension #{ARGV.join(' ')}`.lines.map { Entry.parse _1 }.compact
entries.each(&:move)
@12joan
Copy link
Author

12joan commented Jun 30, 2024

Warning: May overwrite files whose paths are identical up to the first dot. May cause disastrous results for paths containing a dot in a directory name.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment